Pattabhi
Pattabhi

Reputation: 855

Creating Parent Property in JSON

I have requirement to create a parent and child property of JSON from same object which means it should be like

 {"employee": {
   "name":"skanda", 
   "id":"123", 
   "employee":[
      {"id":"345"}
      ]
     }
  }

Here is my Java Object. Please let me know how can I do this. Should I create Inner classes and have instance of one more Employee object. Please advise. I have to design in such a way that the same should also be De-serialized on other end when passed through Rest WS. If I can use annotations please advise which annotations should be used in this case.

public class Employee {
  private String name;
  private String id;
  private List<Employee> list = new ArrayList<Employee>();

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getId() {
    return id;
}

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

public List<Employee> getList() {
    return list;
}

public void setList(List<Employee> list) {
    this.list = list;
}

}

Upvotes: 1

Views: 2339

Answers (2)

Bruno Ribeiro
Bruno Ribeiro

Reputation: 6217

You can use Jackson and annotations. You will need "jackson-databind".

On maven, add the dependency like this:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.4</version>
</dependency>

With a POJO like this:

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

@JsonRootName(value = "employee")
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
public class Employee {

    private String name;

    private String id;

    private List<Employee> employee;

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

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

    public List<Employee> getEmployee() {
        return employee;
    }

    public void setEmployees(final List<Employee> employee) {
        this.employee = employee;
    }

}

And an example like this:

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class EmployeeTest {

    private static final String EXPECTED_JSON_RESULT = "{\"employee\":{\"@id\":1,\"name\":\"skanda\",\"id\":\"123\",\"employee\":[{\"@id\":2,\"id\":\"345\"}]}}";

    @Test
    public void serializationTest() throws JsonProcessingException {
        final Employee emp1 = new Employee();
        emp1.setId("123");
        emp1.setName("skanda");

        final Employee empL1 = new Employee();
        empL1.setId("345");

        final List<Employee> list = new ArrayList<>();
        list.add(empL1);

        emp1.setEmployees(list);

        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(Include.NON_NULL);
        objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);

        Assert.assertEquals(EXPECTED_JSON_RESULT, objectMapper.writeValueAsString(emp1));
    }

}

Will generate a JSON like this:

{
    "employee":{
        "@id":1,
        "name":"skanda",
        "id":"123",
        "employee":[
            {
                "@id":2,
                "id":"345"
            }
        ]
    }
}

@JsonIdentityInfo will help you on self-references, avoiding StackOverflowError and is mapped for @idproperty. You can remove, if you want.

For complete documentation, see https://github.com/FasterXML/jackson

Upvotes: 1

Invisible Arrow
Invisible Arrow

Reputation: 4925

You can achieve this using Jackson JSON library: http://jackson.codehaus.org/

One good tutorial which particularly addresses nested objects is here: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

Apart from these, Google is your friend :)

Upvotes: 0

Related Questions