使用Java排序Json对象

时间:2018-10-23 08:46:03

标签: java android json

我正在尝试对从REST API调用获得的Json响应进行排序。通话后我得到的结果是无序的。

这是示例JSON:

{
 "result": [{
             "key1": "value1",
             "key2": "value2",
             "number": "102",  
            },
            {
             "key1": "value3",
             "key2": "value4",
             "number": "101",  
            }] 
}

我希望响应基于“数字”进行排序,如下所示:

{
 "result": [{
             "key1": "value3",
             "key2": "value4",
             "number": "101",  
            },
            {
             "key1": "value1",
             "key2": "value2",
             "number": "102",  
            }] 
}

这是我解析JSON的代码:

try {
     HttpGet httpget = new HttpGet("Some API URL");
     httpget.setHeader("Accept", "application/json");
     System.out.println("Executing request " + httpget.getRequestLine());
     CloseableHttpResponse response = httpclient.execute(httpget);
     try {
          System.out.println("----------------------------------------");
          System.out.println(response.getStatusLine());
          String responseBody = EntityUtils.toString(response.getEntity());
          System.out.println(responseBody);
          System.out.println("----------------------------------------");
          JSONObject jobj = new JSONObject(responseBody);
          JSONArray result = jobj.getJSONArray("result"); 
          int n = result.length();
          for (int i = 0; i < n; ++i) {
               System.out.println("------");
               JSONObject incident = result.getJSONObject(i);
               System.out.println(incident.getString("number"));
               System.out.println(incident.getString("short_description"));
               System.out.println("------"); 
          } 
         } finally {
             response.close();
        }
       } finally {
           httpclient.close();
      }       

有人可以帮忙吗?

0 个答案:

没有答案