0

I'm trying to build an array of objects, something like this

     [
      { name: "joe", id: "123"},
      { name: "ken", id: "234"},
      { name: "dave", id: "987"}
    ]

End goal is to return this as a JSON object in API response. I'd like to use JSON.simple, Greatly appreciate any suggestions,

I am sure there is better way to code, below is what I have currently,

am sure there is better way to code, below is what I have currently,
    JSONObject obj1 = new JSONObject();
        obj1.put("id", "123");
        obj1.put("name", "joe");
    JSONObject obj2 = new JSONObject();
        obj2.put("id", "234");
        obj2.put("name", "ken");
    JSONObject obj3 = new JSONObject();
        obj3.put("id", "987");
        obj3.put("name", "dave");
        JSONArray list = new JSONArray();
    list.add(obj1);
    list.add(obj2);
    list.add(obj3);

1 Answer 1

1

You should define a Class representing the data you want to transform into JSon

class Person {
   private String name;
   private String id;
}

Then use a Serialization library to transform the object list to JSon.

For example : https://github.com/FasterXML/jackson

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.