如何使用jackson将json列表序列化为POJO?

时间:2016-04-23 10:02:57

标签: java json jackson

以下是我的json列表,其中包含2个POJO条目:

[{"userEmail":null,"userId":5,"userName":"rahul","userPassword":"asd",},  {"addressId":1,"userApartment":"YSR skyline","userCity":"Bangalore","userId":5,"userLocality":"Venkateshwara Layout","userStreet":"Mahadevapura"}]

每个POJO的定义如下:

public class UserLoginDataObj {

private int userId;
private String userName;
private String userEmail;
private String userPassword;

public String getUserPassword() {

    return userPassword;
}

public void setUserPassword(String userPassword) {
    this.userPassword = userPassword;
}

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getUserEmail() {
    return userEmail;
}

public void setUserEmail(String userEmail) {
    this.userEmail = userEmail;
}  }

public class AddAddressObj {
private String userApartment;
private String userStreet;
private String userLocality;
private String userCity;
private int addressId;
private int userId;


public int getAddressId() {
    return addressId;
}

public void setAddressId(int addressId) {
    this.addressId = addressId;
}

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}

public String getUserApartment() {
    return userApartment;
}

public void setUserApartment(String userApartment) {
    this.userApartment = userApartment;
}

public String getUserStreet() {
    return userStreet;
}

public void setUserStreet(String userStreet) {
    this.userStreet = userStreet;
}

public String getUserLocality() {
    return userLocality;
}

public void setUserLocality(String userLocality) {
    this.userLocality = userLocality;
}

public String getUserCity() {
    return userCity;
}

public void setUserCity(String userCity) {
    this.userCity = userCity;
}}

我需要使用JACKSON

将数据从json序列化到这两个POJO类

感谢任何帮助。 提前致谢。 :)

2 个答案:

答案 0 :(得分:0)

Arpit,

您需要再添加一个名为User的类,其中包含这两个POJO,这些POJO将被反序列化以为您提供这些类:

package com.yourpackage.model;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.yourpackage.deserializer.UserDeserializer;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
    private UserLoginDataObj obj;
    private AddAddressObj address;

    public UserLoginDataObj getUserLoginDataObj() {
        return obj;
    }

    public void setUserLoginDataObj(UserLoginDataObj obj) {
        this.obj = obj;
    }

    public AddAddressObj getAddAddressObj() {
        return address; 
    }

    public void setAddAddressObj(AddAddressObj address) {
        this.address = address;
    }
}

添加此类后,现在可以使用以下代码反序列化 -

package com.yourpackage.deserializer;

import java.io.IOException;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.yourpackage.model.AddAddressObj;
import com.yourpackage.model.User;
import com.yourpackage.model.UserLoginDataObj;

public class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

        ObjectCodec oc = jsonParser.getCodec();
        JsonNode nodes = oc.readTree(jsonParser);

        UserLoginDataObj obj = new UserLoginDataObj();
        AddAddressObj address = new AddAddressObj();

        for(int i = 0; i < nodes.size(); i++) {
            JsonNode node = nodes.get(i);

            Iterator<String> fields = node.fieldNames();
            boolean isUser = false;

            while(fields.hasNext()) {
                String field = fields.next();

                if(!field.equals("userId")) {
                    if(field.equals("userEmail") || field.equals("userName") || field.equals("userPassword")) {
                        isUser = true;
                        break;
                    }
                }
            }

            if(isUser) {
                String userEmail = "", userName = "", userPassword = "";
                int userId = 0;

                try {
                    userEmail = node.get("userEmail").textValue();
                } catch(Exception e) {
                    userEmail = null;
                }

                try {
                    userName = node.get("userName").textValue();
                } catch(Exception e) {
                    userName = null;
                }

                try {
                    userPassword = node.get("userPassword").textValue();
                } catch(Exception e) {
                    userPassword = null;
                }

                try {
                    userId = node.get("userId").intValue();
                } catch(Exception e) {
                    userId = 0;
                }

                obj.setUserEmail(userEmail);
                obj.setUserId(userId);
                obj.setUserName(userName);
                obj.setUserPassword(userPassword);

            } else {
                String userApartment = "", userStreet = "", userLocality = "", userCity = "";
                int addressId = 0;
                int userId = 0;

                try {
                    userApartment = node.get("userApartment").textValue();
                } catch(Exception e) {
                    userApartment = null;
                }

                try {
                    userStreet = node.get("userStreet").textValue();
                } catch(Exception e) {
                    userStreet = null;
                }

                try {
                    userLocality = node.get("userLocality").textValue();
                } catch(Exception e) {
                    userLocality = null;
                }

                try {
                    userCity = node.get("userCity").textValue();
                } catch(Exception e) {
                    userCity = null;
                }

                try {
                    addressId = node.get("addressId").intValue();
                } catch(Exception e) {
                    addressId = 0;
                }

                try {
                    userId = node.get("userId").intValue();
                } catch(Exception e) {
                    userId = 0;
                }

                address.setAddressId(addressId);
                address.setUserApartment(userApartment);
                address.setUserCity(userCity);
                address.setUserId(userId);
                address.setUserLocality(userLocality);
                address.setUserStreet(userStreet);
            }
        }

        User u = new User();

        u.setAddAddressObj(address);
        u.setUserLoginDataObj(obj);

        return u;
    }   
}

我已根据您提供的json文件测试了此代码。

答案 1 :(得分:0)

您可以使用for (var key in stuffData) { var totalSum =0; if(stuffData[key] = 'Fruit'{ for(var i=0; i< stuffData[key].length ; i++){ totalSum+=stuffData[key].price; } } if(stuffData[key] = 'Sport'{ for(var i=0; i< stuffData[key].length ; i++){ totalSum+=stuffData[key].price; } } if(stuffData[key] = 'Kitchen'{ for(var i=0; i< stuffData[key].length ; i++){ totalSum+=stuffData[key].price; } } console.log("TOTAL SUM",totalSum); } 注释将JsonFormat属性设置为shape,以告知Jackson按照here所述从数组项中读取对象属性。

见下面的完整示例。请注意聚合其他两个对象的JsonFormat.Shape.ARRAY类。

User

输出:

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

public class JacksonFormArray {
    static final String JSON = "[{\"userEmail\":null,\"userId\":5,\"userName\":\"rahul\","
            + "\"userPassword\":\"asd\"},  {\"addressId\":1,\"userApartment\":"
            + "\"YSR skyline\",\"userCity\":\"Bangalore\",\"userId\":5,\"userLocality\""
            + ":\"Venkateshwara Layout\",\"userStreet\":\"Mahadevapura\"}]";

    static class UserLoginDataObj {
        public int userId;
        public String userName;
        public String userEmail;
        public String userPassword;

        @Override
        public String toString() {
            return "UserLoginDataObj{" +
                    "userId=" + userId +
                    ", userName='" + userName + '\'' +
                    ", userEmail='" + userEmail + '\'' +
                    ", userPassword='" + userPassword + '\'' +
                    '}';
        }
    }

    static class AddAddressObj {
        public String userApartment;
        public String userStreet;
        public String userLocality;
        public String userCity;
        public int addressId;
        public int userId;

        @Override
        public String toString() {
            return "AddAddressObj{" +
                    "userApartment='" + userApartment + '\'' +
                    ", userStreet='" + userStreet + '\'' +
                    ", userLocality='" + userLocality + '\'' +
                    ", userCity='" + userCity + '\'' +
                    ", addressId=" + addressId +
                    ", userId=" + userId +
                    '}';
        }
    }

    @JsonFormat(shape = JsonFormat.Shape.ARRAY)
    @JsonPropertyOrder({ "login", "address"})
    static class User {
        public UserLoginDataObj loging;
        public AddAddressObj address;

        @Override
        public String toString() {
            return "User{" +
                    "loging=" + loging +
                    ", address=" + address +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(JSON, User.class));
    }
}