使用Gson解析JSON列表

时间:2015-06-25 22:37:35

标签: java json parsing gson

我试图用Gson解析JSON文件,但我在尝试获取所有值时遇到了很多问题。 JSON的结构可以在下一张图片中看到:

enter image description here

正如您所看到的,它是一个推文列表'我需要在文件中写入的jsons(不是数组,没有括号)(每行一个)。问题是,我如何解析这个JSON并单独发送每条推文?

2 个答案:

答案 0 :(得分:1)

这样的事情会让你接近。 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": ""
    }
  }
}

答案 1 :(得分:1)

我最终这样做了:

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();
    }
}

这样我就不需要新课了。不确定它是否是最佳解决方案,但它确实有效。