【问题标题】:How can I Parse an Object which is an array of JSONS coming from an URL?如何解析来自 URL 的 JSONS 数组的对象?
【发布时间】:2021-11-28 03:43:52
【问题描述】:

我正在调用一个 URL 并得到如下所示的响应。我无法解析它。谁能告诉我如何解析数组中的对象?

Object[] response = restTemplate.exchange(url, HttpMethod.GET, item, Object[].class);

JSON:

[
   {
      "name":"abc",
      "description":"Data",
      "createdBy":"abc",
      "id":"30D8000506",
      "models":[
         {
            "description":"Data",
            "id":"dcfdf",
            "Planning":false
         }
      ],
      "changedBy":"abc",
      "openURL":"ABC"
   },
   {
      "name":"louis",
      "description":"",
      "createdBy":"abc",
      "id":"583E3817216",
      "changed":"abc",
      "URL":"ABC"
   },
   {
      "name":"Board",
      "description":"",
      "createdBy":"abc",
      "id":"583E39BB21",
      "changedBy":"abc",
      "openURL":"ABC"
   }
]

【问题讨论】:

    标签: java arrays json spring-boot


    【解决方案1】:

    有几种方法。

    1. 为您的响应对象构建类并使用Jackson 将此响应映射到 POJO 数组。 这将花费更多时间,但它会使响应方式的工作更容易。

    2. 使用JSON 库并使用该库解析响应。然后只获取您需要的值和属性...

    小例子:

    // Get your Json Array 
    
    JSONArray itemArray = new JSONArray(yourJsonString); // Here is your response...
    
    // Get your first Element from your array 
    
    JSONObject firstItem = itemArray.getJSONObject(0); // That would be  "name":"abc", "description":"Data" etc...
    
    // Access any value on your jsonObject
    
    String itemName = firstItem.getString("name"); // "name", "description" , "data" and so on
    

    【讨论】:

      猜你喜欢
      • 2017-05-18
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2015-08-05
      • 1970-01-01
      • 2016-11-28
      相关资源
      最近更新 更多