如果你不想使用 Jackson 库,你可以使用 Java 的原生 JSON 解析库 org.json
。以下是一个使用 org.json
的示例代码:
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class JsonToObjectExample {
public static void main(String[] args) {
String input = "[{\"q\":\"b\"},{\"f\":\"t\"}]";
try {
// 将 JSON 字符串转换为 JSONArray
JSONArray jsonArray = new JSONArray(input);
// 遍历 JSONArray
List<String> qValues = new ArrayList<>();
for (Object obj : jsonArray) {
if (obj instanceof JSONObject) {
// 将 Object 转换为 JSONObject
JSONObject jsonObject = (JSONObject) obj;
// 获取键为 "q" 的值
String qValue = jsonObject.optString("q");
qValues.add(qValue);
}
}
// 遍历结果
for (String qValue : qValues) {
System.out.println("Value of 'q': " + qValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个示例中,我们使用 org.json.JSONArray
和 org.json.JSONObject
类来解析 JSON 字符串。同样,请确保在实际应用中进行适当的异常处理。