java如何解析以下JSON

时间:2018-04-22 12:05:47

标签: java json

我是JSON的新手。我从服务器获得了以下json文件:

      [{"status":0,"hq":[["2018-04-20","11.51","11.35","-0.12","-1.05%","11.20","11.58","958691","109080.12","0.57%"],["2018-04-19","11.52","11.47","-0.03","-0.26%","11.42","11.69","849132","97959.35","0.50%"]],"code":"cn_000001","stat":["累计:","2018-04-19至2018-04-20","-0.15","-1.30%",11.2,11.69,1807823,207039.47,"1.07%"]}]

我需要获得两条记录:

     1."2018-04-20","11.51","11.35","-0.12","-1.05%","11.20","11.58","958691","109080.12","0.57%"
     2."2018-04-19","11.52","11.47","-0.03","-0.26%","11.42","11.69","849132","97959.35","0.50%"

我如何解析它和java lib?谢谢你的帮助!

PS。我试过GSON,尝试解析JSON来映射,

   Map<String, Object> map = new Gson().fromJson(result, new TypeToken<Map<String, Object>>(){}.getType());
                map.forEach((x,y)-> System.out.println("key : " + x + " , value : " + y));

并得到以下例外:

  Exception in thread "AWT-EventQueue-0" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

所以现在我不知道该怎么做。请帮忙。谢谢。

1 个答案:

答案 0 :(得分:0)

我建议使用此库:https://mvnrepository.com/artifact/org.json/json/20180130

我在这里写样本供您参考:

JSONOArray jSONOArray = new JSONOArray([{"status":0,"hq":[["2018-04-20","11.51","11.35","-0.12","-1.05%","11.20","11.58","958691","109080.12","0.57%"],["2018-04-19","11.52","11.47","-0.03","-0.26%","11.42","11.69","849132","97959.35","0.50%"]],"code":"cn_000001","stat":["累计:","2018-04-19至2018-04-20","-0.15","-1.30%",11.2,11.69,1807823,207039.47,"1.07%"]}]);
 JSONObject jsonObj = jSONOArray.get(0);
 JSONOArray array = jsonObj.get("hq");

您将获得数组并迭代数组以获取内部元素。