如何从响应中提取 json 数据 - Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26291995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract json data from the response - Java
提问by Nandan Bhat
I am trying to extract data from Json string which is obtained by a response using only Java code. I am posting my Java code here.
我正在尝试从仅使用 Java 代码的响应中获取的 Json 字符串中提取数据。我在这里发布我的 Java 代码。
OUTPUT:
输出:
Entering into while loop
[{"name":"Frank","food":"pizza","quantity":3}]
This is my Java code.
这是我的Java代码。
public void receive()
{
System.out.println("Entering into sendNote method");
try {
// make json string,
String json = "{\"name\":\"Frank\",\"food\":\"pizza\",\"quantity\":3}";
// send as http get request
URL url1 = new URL("http://myurl/file.php?usersJSON="+userList);
URLConnection conn1= url1.openConnection();
//I am receiving exactly what I have sent....
BufferedReader rd = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
{
System.out.println("Entering into while loop");
System.out.println(line);// line contains the received json parameters
//I want to enter the recieved parameters into my database
//
//
//
//I need the solution right here....
}
rd.close();
}
catch (Exception e)
{
System.out.println("Error Occured while receiving");
e.printStackTrace();
}
}
Thank you !!!!!
谢谢 !!!!!
@Ankur: This is how I tried,
@Ankur:这就是我尝试的方式,
@ Lahiru Prasanna, @ankur-singhal Thanks a lot.!!
@ Lahiru Prasanna,@ankur-singhal 非常感谢。!!
回答by Ankur Singhal
There are few ways to achive the same.
有几种方法可以实现相同的目标。
1.) Create a response pojo
1.) 创建一个 response pojo
MyResponse ob = new ObjectMapper().readValue(jsonString, MyResponse.class);
// then call getters on above.
// 然后调用上面的 getter。
2.) Get key/values
2.) 得到 key/values
JSONObject json = (JSONObject)new JSONParser().parse(""name":"Frank","food":"pizza","quantity":3}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("food"));
3.) Converting Json
to HashMap
3.) 转换Json
为HashMap
public static void main(String[] args) {
try {
jsonToMap("{\"name\":\"Frank\",\"food\":\"pizza\",\"quantity\":3}");
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
System.out.println("json : " + jObject);
System.out.println("map : " + map);
}
output
输出
json : {"name":"Frank","food":"pizza","quantity":3}
map : {food=pizza, name=Frank, quantity=3}
回答by Lahiru Prasanna
I think that you successfully got HttpResponse.here variable called response is HttpResponse.
我认为您成功获得了 HttpResponse.here 变量,称为 response 是 HttpResponse。
// Could do something better with response.
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
content.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
JSONObject jsonObject = new JSONObject(builder.toString());
} catch (JSONException e) {
System.out.println("Error parsing data " + e.toString());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.toString());
System.out.println( "" + e.toString());
System.out.println("" + e.toString());
}
And important thing is never use Strings for json operations.
重要的是永远不要将字符串用于 json 操作。
you can retrieve your data from jsonObject like this
您可以像这样从 jsonObject 检索数据
String name = jsonObject.getString("name");