我如何使用Httpclient循环返回的JSON

时间:2012-12-02 11:16:36

标签: java httpclient

我有以下代码用于调用返回具有以下格式的JSON的API: -

{
  "data": [
    {
      " Ser": 1,
      " No": 1
    },
    {
      " Ser": 2,
      " No": 2
    },
    {
      " Ser": 3,
      " No": 3
    },
    {
      " Ser": 4,
      " No": 4
    },
    {
      " Ser": 5,
      " No": 5
    },

  ]
}

代码是: -

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("/json/api/getinfo?type=100");
    HttpResponse response = client.execute(request);
// Get the response, how i can loop through the returned JSON and assign the reterned json to a global parameters which i can access from ym system using has values #parameter1# , #parameter2#, etc.

那么如何循环返回的JSON并将其“NO”分配给全局参数? 最诚挚的问候

1 个答案:

答案 0 :(得分:1)

您应该通过documentation中提到的HttpReponseHttpEntity.getContent()对象中获取内容。然后,内容应从json.org/java中的任何JSON库提供给JSONObject。然后,您可以通过JSONObject遍历JSON输出并从中提取元素。

HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) 
{
    //
    // Using Commons IO library's IOUtils method 
    // to read the content from the stream.
    //
    String json = IOUtils.toString(entity.getContent());
    JSONObject obj = new JSONObject(json);
    // Process the JSON

    // shutdown the connection.
}