1


I have a java.util.List containing Java POJOs that I want to render as JSON Array String. For example:

[
  { "name": "abc", "age": 50 },
  { "name": "def", "age": "25" }
];

Using Java EE JSON Api I have added:

public String createJsonArrayFromList(List<Person> list) {
    JsonArrayBuilder jsonArray = Json.createArrayBuilder();
    for(Person c : list) {
        jsonArray.add(Json.createObjectBuilder()
                .add("name", c.getName())
                .add("surname", c.getSurname()));
    }
    JsonArray array =jsonArray.build();
    return array.toString();
}

However, what is returned is not the JSON String array but "org.glassfish.json.JsonArrayBuilderImpl@761c5d2f"

I have attemped with:

StringWriter buffer = new StringWriter();
Json.createWriter(buffer).writeObject(array);

But writeObject expects a different object type rather than JsonArray. Any help?

2 Answers 2

4

Use writeArray instead of writeObject:

JsonArray arr = ...;
JsonWriter writer = Json.createWriter(...)
writer.writeArray(arr);
writer.close();

See the docs.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Gson Library which helps you better.

GsonBuilder builder=new GsonBuilder();
Gson gson=builder.create();
List<YourMeberClas> YourList=new ArrayList<>();
JsonElement je = gson.toJsonTree(YourList, new 
TypeToken<List<YourMemberClass>>() {
            }.getType());

With this you can easily access the data as well.

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.