[英]How can I convert the following JSON string to Java Object by Gson?
[英]How can i convert JSON data present in a URL into a JSON string in java or android?
我在下面的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中的值為JSON數據,請打開以查看它 。
我如何獲取此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和value,因此您必須像這樣迭代整個集合(如果您知道響應中使用的鍵,則無需使用此方法)。
Iterator<?> keys = jsonObj.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
System.out.print("key - value"+ key + jsonObj.getString(key));
}
為了僅從json響應中獲取值,您需要解析json:
像這樣
JSONObject jsonObj = new JSONObject("{ "one": "two", "key": "value" }"); // your data string
String valOne = jsonObj.getString("one");
String valKey = jsonObj.getString("key");
檢查以下示例以解析如何解析Json
希望這可以幫助您.. :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.