我想用Gson解析JSON文件,但是我有很多問題試圖獲取所有值。在JSON的結構可以看到下一張圖片中:用Gson解析JSON列表
正如你可以看到,這是推特jsons的列表(不是數組,不帶括號),我需要在一個寫文件(每行一個)。問題是,我該如何解析這個JSON並分別獲取每條推文?
我想用Gson解析JSON文件,但是我有很多問題試圖獲取所有值。在JSON的結構可以看到下一張圖片中:用Gson解析JSON列表
正如你可以看到,這是推特jsons的列表(不是數組,不帶括號),我需要在一個寫文件(每行一個)。問題是,我該如何解析這個JSON並分別獲取每條推文?
這樣的事情會讓你接近。 JsonTestFiles.getJson(「tweets.json」)只是將json作爲一個字符串返回,這就是你開始的。
@Test
public void testGson() {
Gson gson = new Gson();
Tweets tweets = gson.fromJson(JsonTestFiles.getJson("tweets.json"), Tweets.class);
System.out.println(tweets);
}
private static class Tweets {
public Map<String, Data> id;
@Override
public String toString() {
return "Tweets{" +
"id=" + id +
'}';
}
}
private static class Data {
public String created_at;
public int id;
public String id_str;
public String text;
public String source;
public boolean truncated;
public String in_reply_to_status_id;
@Override
public String toString() {
return "Data{" +
"created_at='" + created_at + '\'' +
", id=" + id +
", id_str='" + id_str + '\'' +
", text='" + text + '\'' +
", source='" + source + '\'' +
", truncated=" + truncated +
", in_reply_to_status_id='" + in_reply_to_status_id + '\'' +
'}';
}
}
和JSON:
{
"id": {
"50413592" : {
"created_at" : "Sunday",
"id" : 50413592,
"id_str" : "50413592",
"text" : "Hello text",
"source":"the source",
"truncated": false,
"in_reply_to_status_id": ""
},
"50413593" : {
"created_at" : "Sunday",
"id" : 50413593,
"id_str" : "50413593",
"text" : "Hello text",
"source":"the source",
"truncated": false,
"in_reply_to_status_id": ""
},
"50413594" : {
"created_at" : "Sunday",
"id" : 50413594,
"id_str" : "50413594",
"text" : "Hello text",
"source":"the source",
"truncated": false,
"in_reply_to_status_id": ""
}
}
}
我落得這樣做:
JsonObject jsonObject = parser.parse(line).getAsJsonObject();
JsonObject o = jsonObject.get("id").getAsJsonObject();
JsonArray tweets = parser.parse("[" + o.toString() + "]").getAsJsonArray();
for (JsonElement element : tweets) {
for (Map.Entry<String, JsonElement> entry : element.getAsJsonObject().entrySet()) {
String tweet = entry.getValue().toString();
}
}
這樣,我並不需要一個新的類。不知道它是否是最好的解決方案,但它的工作原理。
這應該有點幫助http://www.jsonschema2pojo.org/ – Pshemo
[org.json](https://github.com/douglascrockford/JSON-java/blob/master/JSONObject.java)庫可以幫助你。 – Andrew
@Pshemo這是一個非常酷的工具,但我只需要獲取每條推文和一個字符串。 –