如何从响应中提取 json 数据 - Java [英] How to extract json data from the response - Java
本文介绍了如何从响应中提取 json 数据 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从仅使用 Java 代码的响应中获取的 Json 字符串中提取数据.我在这里发布我的 Java 代码.
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.
输出:
Entering into while loop
[{"name":"Frank","food":"pizza","quantity":3}]
这是我的 Java 代码.
This is my Java code.
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();
}
}
谢谢!!!!!!
@安库尔:我就是这样试的,
@Ankur: This is how I tried,
@Lahiru Prasanna,@ankur-singhal非常感谢.!!
@ Lahiru Prasanna, @ankur-singhal Thanks a lot.!!
推荐答案
我认为你成功获得了 HttpResponse.这里的变量叫做 response 是 HttpResponse.
I think that you successfully got HttpResponse.here variable called response is 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());
}
重要的是永远不要将字符串用于 json 操作.
And important thing is never use Strings for json operations.
您可以像这样从 jsonObject 检索数据
you can retrieve your data from jsonObject like this
String name = jsonObject.getString("name");
这篇关于如何从响应中提取 json 数据 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文