java - gson怎么判断json中的key是否存在
怪我咯
怪我咯 2017-04-18 10:25:51
0
1
1356

部分json文件如下:


{
  "statuses": [
    {
      "created_at": "Fri Dec 02 17:05:40 +0800 2016",
      "id": 4048283825629844,
      "mid": "4048283825629844",
      "idstr": "4048283825629844",
      "text": "前卫 //@主治医湿:造型有点害怕 //@冷知君:原谅我不懂时尚 //@城南邮局:最后是刘梓晨吧 //@话提:走远了……",
      "source_allowclick": 0,
      "source_type": 1,
      "source": "<a href=\"http://app.weibo.com/t/feed/6e3owN\" rel=\"nofollow\">iPhone 7 Plus</a>",
      "favorited": false,
      "truncated": false,
      "in_reply_to_status_id": "",
      "in_reply_to_user_id": "",
      "in_reply_to_screen_name": "",
      "pic_urls": [],
      "geo": null,
      "user": {
        "id": 5680719858,
        "idstr": "5680719858",
        "class": 1,
        "screen_name": "综艺博主",

我是使用gson来解析的,代码如下:


public class Main {

    public static void main(String[] args) throws IOException {
       
            Gson gson = new Gson();
            jsonstring abc = gson.fromJson(json,jsonstring.class);
            List<statuses> statuses = abc.getStatuses();
            for (statuses st : statuses){
                System.out.println(st.getUser().getScreen_name());
            }
        }
    }
}
//json最外层的内容
class jsonstring{
    private List<statuses> statuses;
    private String hasvisible;

    public List<com.lizhao.statuses> getStatuses() {
        return statuses;
    }
    
    public String getHasvisible() {
        return hasvisible;
    }
}
//包含statuses中的key
class statuses{
    private String created_at;
    private String text;
    private user user;

    public com.lizhao.user getUser() {
        return user;
    }

    public String getCreated_at() {
        return created_at;
    }

    public String getText() {
        return text;
    }
}
//是statuses里边user这个key的内容
class user{
    private String id;
    private String screen_name;
    private String description;

    public String getDescription() {
        return description;
    }

    public String getId() {
        return id;
    }

    public String getScreen_name() {
        return screen_name;
    }
}

存在一种情况是,user这个key不存在。

我应该怎么判断user这个key是否存在呢?

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
刘奇

If the user key does not exist, statuses.getUser() will be null after deserialization

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template