【问题标题】:如何使用java从Json中检索数据
【发布时间】:2022-01-23 09:49:54
【问题描述】:

大家好,我有这样的 json 响应

  Response response = service.execute(requestSendToNS);
       // JSONObject jsonResponse = new JSONObject(response);
        //String data = jsonResponse.getString("id");
        System.out.println("Response Body : " + response.getBody());

结果如下:

Response Body : [{"status":"success","message":"update success","id":"1404","internalid":2604},{"status":"failed","message":"bad location is already used in another location","id":1405}]

我的问题是如何从我的 json 响应中获取值“id”?

我已尝试使用此代码:

// JSONObject jsonResponse = new JSONObject(response);
        //String data = jsonResponse.getString("id");

我也用过这个 列出 responseObject = objectMapper.readValue(response.getBody(),List);

但我无法从 json 数组映射到对象

但我无法从 id 中检索值

【问题讨论】:

  • 你可以使用像 Gson 或 ObjectMapper 这样的 json 序列化器/反序列化器库
  • 你可以使用com.fasterxml.jackson.databind.ObjectMapper,它有一个方法readValue,它将接受final String json, Class<T> type并返回<T>

标签: java json


【解决方案1】:

首先,您必须创建一个与JSON 响应具有完全相同结构的类,然后您可以使用jackson 库中的ObjectMapperJSON 写入类并从其中读取值它。

【讨论】:

    【解决方案2】:

    您的响应正文是一个数组。

    [{...},{...}]
    

    这就是为什么你不能得到 id

    String data = jsonResponse.getString("id");
    

    请查看 JsonReader 以将 json 读取为 JsonArray

    https://docs.oracle.com/javaee/7/api/javax/json/JsonReader.html#readObject--

    JsonReader jsonReader = Json.createReader(new StringReader(response.getBody()));
    JsonArray array = jsonReader.readArray();
    JsonObject obj = array.getJsonObject(0);
    String data = obj.getString("id");
    

    【讨论】:

    • 我在 java 11 上找不到 Json.createReader...如何在 java 11 上读取它,因为我需要更改参考名称@Huy Nguyen
    • docs.oracle.com/javaee/7/api/javax/json/JsonReader.html, java11 也支持 java 7 ...所以我猜代码仍然适用于更高的 java 版本
    • 但是当我检查我的 intellij 时,我得到了错误红线....
    • 你可以看一下jackson api或gson api,那些库对json的支持非常好......以防你不能使用JsonReader......
    猜你喜欢
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 2019-03-16
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    相关资源
    最近更新 更多