JSON 对象文本必须以“{”开头,位于 1 [字符 2 行 1] 处,并显示“{”错误

2022-09-01 18:24:39
String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";

JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("get");
Object level = getSth.get("2");

System.out.println(level);

我推荐了许多解析此链接的解决方案,但仍然遇到同样的错误。任何人都可以给我一个简单的解决方案来解析它。


答案 1

你的问题是不是.
您要做的是打开与“http://www.json-generator.com/j/cglqaRcMSW?indent=4”的连接并解析 JSON 响应String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";JSONHTTP

String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";
JSONObject jsonObject = new JSONObject(JSON); // <-- Problem here!

不会打开与网站的连接并检索内容。


答案 2

虽然 json 以 “[” 开头,以 “]” 结尾,这意味着这是 Json 数组,请使用 JSONArray:

JSONArray jsonArray = new JSONArray(JSON);

然后,如果需要,可以使用列表测试对象映射它:

ObjectMapper mapper = new ObjectMapper();
List<TestExample> listTest = mapper.readValue(String.valueOf(jsonArray), List.class);