fastJson在bean中加入@JsonProperty转换出的对象中依然有字段为null的处理

前端之家收集整理的这篇文章主要介绍了fastJson在bean中加入@JsonProperty转换出的对象中依然有字段为null的处理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.转换的代码如下

String json = "{\"id\":1059827483,\"idstr\":\"1059827483\",\"class\":1,\"screen_name\":\"DancingToDeath\"}";
        System.out.println(json);
        U u = JSONObject.parSEObject(json,U.class);
        System.out.println(u.getId());
        System.out.println(u.getIdstr());
        System.out.println(u.getMyClass());
        System.out.println(u.getScreen());

2.U实体定义如下:
public class U {

    private long id;
    private String idstr;
    @JSONField(name = "class")
    private int myClass;
    @JsonProperty("screen_name")
    private String screen;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getIdstr() {
        return idstr;
    }

    public void setIdstr(String idstr) {
        this.idstr = idstr;
    }

    public int getMyClass() {
        return myClass;
    }

    public void setMyClass(int myClass) {
        this.myClass = myClass;
    }

    public String getScreen() {
        return screen;
    }

    public void setScreen(String screenName) {
        this.screen = screenName;
    }

}
3.转换结果:
{"id":1059827483,"idstr":"1059827483","class":1,"screen_name":"DancingToDeath"}
1059827483
1059827483
1
null
可见,screen_name并未转换出来,原因在于,对于普通的json解析类,用JsonProperty可以,但是在用fastJson进行解析时,需要用@JSONField(name = "screen_name")来进行标注。

4.改变U

private long id;
    private String idstr;
    @JSONField(name = "class")
    private int myClass;
    @JSONField(name = "screen_name")
    private String screen;
5.转换结果如下:

1059827483
1059827483
1
DancingToDeath


以此记录,希望能帮助到遇到同样问题的人。

猜你在找的Json相关文章