Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

Serializing a List of Objects in Java to json

Currently i am trying to serialize a list of objects to array using Jackson . The Scenario here is if the list contains only one element , the list should be serialised as an object but not like an array . Is there any provision to do that?

I Created a Java Model and i am serialising to JSON using the below Code

A testObject = new A();
    ObjectMapper mapper = new ObjectMapper();           
            String json = mapper.writeValueAsString(testObject);
            System.out.append (json)

DataModel

class A{
private B b;
}

Class B{
private ArrayList<C> c;
}

Class c
{
private int i;
private String test;
}

Upvotes: 1

Views: 3962

Answers (2)

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

Found a SerializationFeature WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED by which we can obtain the above mentioned scenario in JSON

Upvotes: 1

Alexandros
Alexandros

Reputation: 733

Is this what you are looking for?

String json = mapper.writeValueAsString(!CollectionUtils.isEmpty(testObject) && testObject.size()==1? testObject.get(0):testObject);

Upvotes: 0

Related Questions