Java中优化的JSON解析

时间:2015-03-13 06:09:49

标签: java json parsing gson

我正在尝试用Java解析一个大的JSON对象。

{
"created_at":"Fri May 23 18:40:13 +0000 2014",
"id":469910689948389376,
"id_str":"469910689948389376",
"text":"Foto: Discorsi - Scarica l'app e Partecipa http:\/\/t.co\/zqztInkl6h #BraccialettiRossi http:\/\/t.co\/JeGHPvljwn",
"source":"\u003ca href=\"http:\/\/www.apple.com\" rel=\"nofollow\"\u003eiOS\u003c\/a\u003e",
"truncated":false,
"in_reply_to_status_id":null,
"in_reply_to_status_id_str":null,
"in_reply_to_user_id":null,
"in_reply_to_user_id_str":null,
"in_reply_to_screen_name":null,
"user":{
"id":587593116,
"id_str":"587593116",
"name":"Giulia Zaytsev",
"screen_name":"giubex",
...
}

我需要从对象中提取以下信息:

id_str
created_at
text
user_id

有2亿个这样的行,我需要对单个对象进行一些处理(检查它们是否为空)。我试图实现列出的代码here,但我有点困惑。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

首先初始化 gson 和您的模型类:

    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();

    Item item =  gson.fromJson("your_json",Item.class);
    System.out.println(item.id_str);
    System.out.println(item.user.id);

<强> Item.java

public class Item {

    public String id_str;
    public String created_at;
    public String text;
    public User user;

    public class User{
       public long id;
    }
}