简体   繁体   中英

How to serialise a json list to POJO using jackson?

Following is my json list which have 2 entries for 2 POJO:

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

Each POJO has been defined as follows:

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;
}  }

and

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;
}}

I need to serialize the data from the json to these two POJO classes using JACKSON

Any help is appreciated. Thanks in advance. :)

Arpit,

You need to add one more class called User which has these two POJOs which will be deserialized to give you those classes:

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;
    }
}

With the addition of this class, now you can deserialize using the following code-

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;
    }   
}

I have tested this code against the json file you have provided.

You can use the JsonFormat annotation to set the shape attribute to JsonFormat.Shape.ARRAY to tell Jackson to read object properties from the array items as described here .

See below the complete example. Note the User class which aggregates two other objects.

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));
    }
}

Output:

User{loging=UserLoginDataObj{userId=5, userName='rahul', userEmail='null', userPassword='asd'}, address=AddAddressObj{userApartment='YSR skyline', userStreet='Mahadevapura', userLocality='Venkateshwara Layout', userCity='Bangalore', addressId=1, userId=5}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM