我在下面的 android 中尝试了代码:-
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://echo.jsontest.com/key/value/one/two");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
JSONArray jsonObj = new JSONArray(entity);
System.out.print("message is"+jsonObj);
}
catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
//Below i am displaying in my layout in my emulator
protected void onPostExecute(String results) {
if (results!=null) {
TextView et = (TextView)findViewById(R.id.data);
et.setText(results);
}
Button b = (Button)findViewById(R.id.getvehicles);
b.setClickable(true);
}
所以当我只使用 getASCIIContentFromEntity(entity) 时,我就能够按原样打印完整的 JSON 数据。但是我只想打印此 URL 中的值 it is JSON data,please open to see it .
我如何获取此 json URL 中的值?
最佳答案
您的响应采用 JSONObject
形式,因此您必须像这样获取它。
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
Object content = EntityUtils.toString(entity);
JSONObject jsonObj = new JSONObject(content.toString());
System.out.print("message is"+jsonObj.toString());
然后你的 JSONObject
包含多个值,你可以使用对的“键”来获取它。
String value = jsonObj.getString(key); //String value = jsonObj.getString("one");
在您的情况下,您想要打印一和二,这意味着 kay 和值,因此您必须像这样迭代整个集合(如果您知道响应中使用的键,则无需使用此方法)。
Iterator<?> keys = jsonObj.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
System.out.print("key - value"+ key + jsonObj.getString(key));
}
关于java - 如何将 URL 中存在的 JSON 数据转换为 java 或 android 中的 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28761834/