[英]Using GSON to parse a json datafeed
我有一個簡單的JSON提要,它返回一個圖像路徑和一組協調。 “坐標”可以具有無限的一組坐標。 在下面的示例中,它只有3套。
{"image":"Some data", "coords": {"0":[0,0], "1":[55,22], "2":[46,65]}}
我將如何使用GSON解析此內容? 我如何為此建立課程?
謝謝
您將很難,因為它不是有效的JSON。
如果是有效的JSON,例如...
{"image":"Some data", "coords": {"0":[0,0], "1":[55,22], "2":[46,65]}}
我相信GSON可以將coords
解析為<String, ArrayList<Integer>>
的map
,但是我需要嘗試進行確認。
添加gson-1.7.1.jar
文件並編寫此類,以從URL獲取所需的JSONObject
或JSONArray
。
public class GetJson {
public JSONArray readJsonArray(String url) {
String read = null;
JSONArray mJsonArray = null;
try {
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = http.execute(post);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
builder.append(str);
}
is.close();
read = builder.toString();
mJsonArray = new JSONArray(read);
} catch (Exception e) {
e.printStackTrace();
}
return mJsonArray;
}
public JSONObject readJsonObject(String url) {
String read = null;
JSONObject mJsonObject = null;
try {
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = http.execute(post);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
builder.append(str);
}
is.close();
read = builder.toString();
mJsonObject = new JSONObject(read);
} catch (Exception e) {
e.printStackTrace();
}
return mJsonObject;
}
}
請享用...
然后要解析JSON,請參閱以下教程,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.