Java 从HTTP响应获取JSON对象
我想从Http get响应中获取Java 从HTTP响应获取JSON对象,java,android,json,Java,Android,Json,我想从Http get响应中获取JSON对象: 以下是Http get的当前代码: protected String doInBackground(String... params) { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(params[0]); HttpResponse response; String result = null; try
JSON
对象:
以下是Http get的当前代码:
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(params[0]);
HttpResponse response;
String result = null;
try {
response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string representation of the HTML request
System.out.println("RESPONSE: " + result);
instream.close();
if (response.getStatusLine().getStatusCode() == 200) {
netState.setLogginDone(true);
}
}
// Headers
org.apache.http.Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return result;
}
现在我只是得到一个字符串对象。如何获取JSON对象。有一个JSONObject构造函数可以将字符串转换为JSONObject:
您需要使用
JSONObject
如下所示:
String mJsonString = downloadFileFromInternet(urls[0]);
JSONObject jObject = null;
try {
jObject = new JSONObject(mJsonString);
}
catch (JSONException e) {
e.printStackTrace();
return false;
}
希望这对您有所帮助。您得到的字符串只是JSON对象。toString()。这意味着您将获得JSON对象,但它是字符串格式的 如果你想得到一个JSON对象,你可以放:
JSONObject myObject = new JSONObject(result);
如果不查看确切的JSON输出,就很难给出一些工作代码。本教程非常有用,但您可以使用以下内容:
JSONObject jsonObj = new JSONObject("yourJsonString");
然后,您可以使用以下命令从该json对象检索:
String value = jsonObj.getString("yourKey");
这不是你问题的确切答案,但这可能会对你有所帮助
public class JsonParser {
private static DefaultHttpClient httpClient = ConnectionManager.getClient();
public static List<Club> getNearestClubs(double lat, double lon) {
// YOUR URL GOES HERE
String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);
List<Club> ret = new ArrayList<Club>();
HttpResponse response = null;
HttpGet getMethod = new HttpGet(getUrl);
try {
response = httpClient.execute(getMethod);
// CONVERT RESPONSE TO STRING
String result = EntityUtils.toString(response.getEntity());
// CONVERT RESPONSE STRING TO JSON ARRAY
JSONArray ja = new JSONArray(result);
// ITERATE THROUGH AND RETRIEVE CLUB FIELDS
int n = ja.length();
for (int i = 0; i < n; i++) {
// GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
JSONObject jo = ja.getJSONObject(i);
// RETRIEVE EACH JSON OBJECT'S FIELDS
long id = jo.getLong("id");
String name = jo.getString("name");
String address = jo.getString("address");
String country = jo.getString("country");
String zip = jo.getString("zip");
double clat = jo.getDouble("lat");
double clon = jo.getDouble("lon");
String url = jo.getString("url");
String number = jo.getString("number");
// CONVERT DATA FIELDS TO CLUB OBJECT
Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
ret.add(c);
}
} catch (Exception e) {
e.printStackTrace();
}
// RETURN LIST OF CLUBS
return ret;
}
}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:
JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");
公共类JsonParser{
私有静态DefaultHttpClient httpClient=ConnectionManager.getClient();
公共静态列表GetNearestClub(双lat,双lon){
//你的网址在这里
String getUrl=Constants.BASE\u URL+String.format(“getClosestClubs?lat=%f&lon=%f”,lat,lon);
List ret=new ArrayList();
HttpResponse响应=null;
HttpGet getMethod=新的HttpGet(getUrl);
试一试{
response=httpClient.execute(getMethod);
//将响应转换为字符串
字符串结果=EntityUtils.toString(response.getEntity());
//将响应字符串转换为JSON数组
JSONArray ja=新JSONArray(结果);
//遍历并检索俱乐部字段
int n=ja.length();
对于(int i=0;i
执行此操作以获取JSON
String json = EntityUtils.toString(response.getEntity());
这里有更多详细信息:为了彻底解决这个问题(是的,我知道这篇文章很久以前就死了…) 如果需要
JSONObject
,请首先从结果中获取字符串
:
String jsonString = EntityUtils.toString(response.getEntity());
然后您可以获得您的JSONObject
:
JSONObject jsonObject = new JSONObject(jsonString);
您在结果字符串中得到了什么?为什么要使用response.getEntity()两次?将JSON对象返回给您连接的Web服务器以向您发送JSON?“是这样吗?”Zapnologica检查我的答案。另请参见agen451 answerHi呼吸暂停综合征。。如果任何答案满足您的需要,请接受它,以便帮助他人轻松获得正确答案。谢谢这是一个字符串而不是JSON!为什么会有这么多选票?这只是一个toString()
function-基本上与OP所做的事情完全相同。至少这消除了OP的大量低开销代码。有关更完整的解决方案,请参阅下面的@Catalin Pirvu帖子。如果是HttpExchange会怎么样?@Renan Bandeira我正在尝试用你的代码将我的http响应转换为json对象,我收到了这个错误错误:(47,50)java:不兼容的类型:java.lang.StringBuffer无法转换为java.util.Map?我的答案是在2013年。我建议您使用改型和Gson/Jackson来处理请求和Json序列化。我如何在c#中完成同样的任务?非常好的教程。“一般来说,所有JSON节点都将以方括号或花括号开始。与{之间的区别是,方括号([)表示JSONArray节点的开始,而花括号({)表示JSONObject。因此,在访问这些节点时,我们需要调用适当的方法来访问数据。如果JSON节点以[]开头,那么我们应该使用getJSONArray()方法。与节点以{开头相同,那么我们应该使用getJSONObject()方法。”
String jsonString = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = new JSONObject(jsonString);