Java 如何使用Httpclient循环返回的JSON
我有以下代码用于调用返回JSON格式的API:-Java 如何使用Httpclient循环返回的JSON,java,httpclient,Java,Httpclient,我有以下代码用于调用返回JSON格式的API:- { "data": [ { " Ser": 1, " No": 1 }, { " Ser": 2, " No": 2 }, { " Ser": 3, " No": 3 }, { " Ser": 4, " No": 4 }, { " Ser": 5, "
{
"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”分配给全局参数呢?
致以最诚挚的问候您应该通过中提到的
HttpEntity.getContent()
从HttpReponse
对象中获取内容。然后,应该将内容从任何JSON库(如中的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.
}
感谢您的回复,但是有没有一个示例或教程可以帮助我。HttpClient文档页面中的示例将帮助您获得JSON内容。然后,根据您决定使用的JSON库,它将有一些示例来将字符串转换为JSONObject以及如何遍历它。因此,我不确定是否会有一个单独的教程/示例涵盖这两个方面。