Search code examples
javareflectionobjectmapper

Using JAVA Reflection how to create custom JSON object mapping


I have a json Object in the below format, I need to assign the values from Json to java object, But the label name in JSON and class is different.

{
  FirstName: "Sample",
  LastName: "LName",
  Address: [
    {
      type: "Temp",
      street: "test stree",
      
    },
    {
      type: "Perm",
      street: "test stree",
      
    }
  ]
}

Class Parent{

private String Name1;
private String Nama2;
private List<Address> address;}

Class Address{

Private String type;

private String data;
}

I wanted to implement the custom object mapper using Java reflection. the mapping is as below, But I am not getting idea to implement this, Any valuable suggestion or usage of external api would help me to achieve the scenario.

Json Object name Jave Class object Name FirstName ---------- Name1 LastName ---------- Name2
Address.type ------- Address class type Address.street ----- Address class data


Solution

  • You would need reflexion if you receive json data with same structure with properties names changing, for example :

    {
      FirstName1: "Sample",
      LastName1: "LName",
      Address1: [
        {
          type1: "Temp",
          street1: "test stree",
          
        },
        {
          type1: "Perm",
          street1: "test stree",
          
        }
      ]
    }
    
    {
      FirstName2: "Sample",
      LastName2: "LName",
      Address1: [
        {
          type2: "Temp",
          street2: "test stree",
          
        },
        {
          type2: "Perm",
          street2: "test stree",
          
        }
      ]
    }
    

    In your case, it rather look like a property name matching issue, you can annotate your java pojo like that :

    public class Parent{
    
      @JsonProperty("FirstName")
      private String Name1;
    
      @JsonProperty("LastName")
      private String Nama2;
    
      private List<Address> address;
    }
       
    public class Address{
        
      private String type;
        
      @JsonPRoperty("street")
      private String data;
    }
    

    Finally you can deserialize your json object using standard Jackson library :

    new ObjectMapper().readValue(json, Parent.class);