fastjson 自定义反序列化

ugmeyewa  于 2021-11-27  发布在  Java
关注(0)|答案(4)|浏览(406)

有下面2段json数据

json1

{
    "result": {
        "msgen": "OK!",
        "msgcn": "成功!",
        "code": 0
    },
    "data": {
        "createTime": 1461682092873,
        "updateTime": 1461682092873,
        "userId": 123456,
        "username": "123456"
    }
}

json2

{
    "result": {
        "msgen": "OK!",
        "msgcn": "成功!",
        "code": 0
    },
    "data": {
        "rows": [
            {
                "createTime": 1461311265000,
                "timeStamp": 1461311265,
                "username": "123456"
            },
            {
                "createTime": 1458201132000,
                "timeStamp": 1458201132,
                "username": "89898989"
            }
        ]
    }
}

但是定义的bean只是想取里面data或者rows的值,json1只取data的值,json2只取rows的值, 如下:

class UserInfo {
    long createTime;
    long updateTime;
    int userId;
    String username;

    ...
}
class UserInfo2 {
    long createTime;
    long timeStamp;
    String username;

    ...
}

有方法能直接使用JSON.parseObject(...)方法来实现反序列化吗?

UserInfo userInfo = JSON.parseObject(json1, ...);
List<UserInfo2> userInfoList = JSON.parseObject(json2, ...);
a7qyws3x

a7qyws3x1#

没有,,
我的解决方案是,多数据进行了一次处理,让后分两次 反序列化的。

bf1o4zei

bf1o4zei3#

@wenshao 能举个例子吗

d4so4syb

d4so4syb4#

@littleGnAl
写javabean:
class Data {
List rows;
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
}

class Response {
Data data;
public Data getData() {
if (data == null) {
data = new Data();
}
return data;
}
public void setData(Data data) {
this.data = data;
}
}

Response response = JSON.parseObject(json2, Response.class);
List rows = response == null ? null : response.getData().getRows();

相关问题