【问题标题】:how to access json array element in java如何在java中访问json数组元素
【发布时间】:2014-09-29 08:04:16
【问题描述】:

我在输出中得到 json 数组。我想从响应中访问特定的关键元素。我怎么能 ..?

 ResponseEntity <String> respone;
      try {
          response =
      restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);



      String response=response.getBody(); 
      JSONObject res = new JSONObject();
      res.put("result", response);
      System.out.println(res);
      int len=res.size();
      System.out.println(len);
      JSONParser parser=new JSONParser();
        Object obj = parser.parse(response);
        JSONArray array = (JSONArray)obj;
        System.out.println(array.get(0)); } 

这是我正在输出的响应格式。我想从响应中访问出价。我该怎么做?

  [
      {
            "bName": "abc", 
            "bId": "n86nbnhbnghgy76"

          }
        ]

【问题讨论】:

  • 杰克逊?格森?帮助您通过元素轻松解析的库
  • @sfat ...我正在使用杰克逊..
  • 您正在使用 JSONParser。如果您的项目中有杰克逊,只需执行 ObjectMapper mapper = new ObjectMapper(); AClassThatMatchesTheModelOfThatJson thatModel = mapper.readValue(response, AClassThatMatchesTheModelOfThatJson.class);

标签: java json rest


【解决方案1】:

使用JSONArray(String json)构造函数解码你的字符串:

String response = response.getBody(); 
JSONArray res = new JSONArray(response);
String bId = res.getJSONObject(0).get("bId");
System.out.println(bid);

【讨论】:

  • 它向我显示了这样的错误 - 此行 JSONArray res = new JSONArray(response); 的构造函数 JSONArray(String) 未定义;
  • ...我正在使用 google json 库。我该如何解决上述错误?
  • 我不使用这个实现。
【解决方案2】:

编辑

尝试以下操作:

  String response=response.getBody(); 
  JSONObject res = new JSONObject();
  System.out.println(res);
  int len=res.size();
  System.out.println(len);
  JSONParser parser=new JSONParser();
    Object obj = parser.parse(response);
    JSONArray array = (JSONArray)obj;
    res=(JSONObject)array.get(0);
    System.out.println(res.get("bId"));

输出:

n86nbnhbnghgy76

这是基于您的代码和Simple Json Library

【讨论】:

  • .still 同样的错误 - 构造函数 JSONArray(String) 未定义
  • 注意JSONArray.fromObject(response);是你应该使用的看第二行。
  • ..它显示了这个错误- JSONArray 类型的 fromObject(String) 方法未定义
  • sourceforge.net/projects/json-lib链接下载json库。你会很高兴的。
  • 我添加了 import org.json.simple.JSONArray; import org.json.simple.JSONObject;this class.but 还是一样的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
  • 2018-05-30
相关资源
最近更新 更多