Razib
Razib

Reputation: 11163

Creating JSON using java library

I am trying to create a JSON as following format -

{
 "approvable" : "true",
 "approvedBy" : [user1, user2, user3, user4]
}

I have two java variables -

boolean approvable;
List<User> approvedBy;

If the approvedBy list contains all the Users, then can I make the JSON directly using any JSON library? Suppose I want to do something like this -

JsonBuilder jb = new JsonBuilder();
jb.add("approvable", true);
jb.add("approvedBy", approvedBy);

Ultimately, all I need to do is to simplifying the making of JSON. Can anyone suggest any good JSON library which give me this support?

Thanks in advance

Upvotes: 0

Views: 263

Answers (1)

Ankur Singhal
Ankur Singhal

Reputation: 26067

API used is flexjson

public static void main(String args[]) throws Exception {

        Child child2 = new Child("ankur", 23);
        Child child1 = new Child("ankurs", 23);
        Child child3 = new Child("ankurss", 21);

        List<Child> childList = new ArrayList<Child>();
        childList.add(child1);
        childList.add(child2);
        childList.add(child3);

        Parent parent = new Parent();
        parent.setApprovable(true);
        parent.setChildList(childList);
        JSONSerializer serializer = new JSONSerializer();
        System.out.println(serializer.exclude("*.class").deepSerialize(parent));

    }

Output

{
    "approvable": true,
    "childList": [
        {
            "age": 23,
            "name": "ankurs"
        },
        {
            "age": 23,
            "name": "ankur"
        },
        {
            "age": 21,
            "name": "ankurss"
        }
    ]
}

Upvotes: 2

Related Questions