0

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

3
  • If you're using the Oracle JSON kit, it sucks. Commented Nov 12, 2014 at 0:45
  • Use Jackson (or Gson I suppose). Both of those libraries support automatic binding between JSON and POJOs. Whatever you do, don't waste your time with manual conversion. Commented Nov 12, 2014 at 0:59
  • 1
    In my opinion/experience, "manual conversion" is less effort (and often fewer lines of code) than dealing with automatic binding to POJOs. The problem is that many people do not take the time to understand JSON and so feel they must use "cookbook" approaches. Commented Nov 12, 2014 at 1:07

1 Answer 1

2

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"
        }
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.