如何在Java中操纵HTTP json响应数据 [英] how to manipulate HTTP json response data in Java

查看:331
本文介绍了如何在Java中操纵HTTP json响应数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HttpGet getRequest=new HttpGet("/rest/auth/1/session/");
getRequest.setHeaders(headers);
httpResponse = httpclient.execute(target,getRequest);

entity = httpResponse.getEntity();

System.out.println(EntityUtils.toString(entity));

以json格式输出如下

Output as follows in json format

----------------------------------------
{"session":{"name":"JSESSIONID","value":"5F736EF0A08ACFD7020E482B89910589"},"loginInfo":{"loginCount":50,"previousLoginTime":"2014-11-29T14:54:10.424+0530"}}
----------------------------------------

我想知道的是如何使用 Java 不将其写入文件?
我想在我的代码中打印姓名,值

What I want to know is how to you can manipulate this data using Java without writing it to a file? I want to print name, value in my code

杰克逊图书馆是首选,但任何人都可以。

Jackson library is preferred but any would do.

提前感谢

推荐答案

您可以使用此JSON 库将您的json字符串解析为JSONObject并从该对象读取值,如下所示:

You may use this JSON library to parse your json string into JSONObject and read value from that object as show below :

JSONObject json = new JSONObject(EntityUtils.toString(entity));
JSONObject sessionObj =  json.getJSONObject("session");
System.out.println(sessionObj.getString("name"));

您需要从您想要读取值的位置读取该对象。在这里你想要 name 的参数,它在 session 对象里面,所以你首先得到<$的值c $ c> session 使用 getJSONObject(KeyString)并使用函数 name 值/javadoc/org/json/JSONObject.html#getString%28java.lang.String%29rel =nofollow> getString(KeyString)如上所示。

You need to read upto that object from where you want to read value. Here you want the value of name parameter which is inside that session object, so you first get the value of session as JSONObject using getJSONObject(KeyString) and read name value from that object using function getString(KeyString) as show above.

这可以帮到你。

这篇关于如何在Java中操纵HTTP json响应数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆