0

I have a JsonArray which I am getting as a result of call to a method and it looks like - ["#group-apiTest2","#group-apiTest3","#group-apiTest4"] I want to insert one more string - "group-apiTest1" in this JsonArray. So far I tried this but got a different output then expected.

String group1 = "#group-apiTest1";
JsonArray existingArray = ["#group-apiTest2","#group-apiTest3","#group-apiTest4"] //For representation purpose only.
JsonObject jsonRequest = Json.createObjectBuilder().add("tags",
                                Json.createArrayBuilder().add(group1).add(existingArray))
                        .build();
                logger.info("REQUEST - {}", jsonRequest);

The output of the logger is - REQUEST - {"tags":["group-apiTest",["#group-apiTest2","#group-apiTest3","#group-apiTest4"]]} instead of - REQUEST - {"tags":["group-apiTest","#group-apiTest2","#group-apiTest3","#group-apiTest4"]}

Please let me know how to get the expected output. Where am I doing wrong? Thanks.

2 Answers 2

1

You are adding string #group-apiTest1 and array ["#group-apiTest2","#group-apiTest3","#group-apiTest4"]. That's why you see the result as ["group-apiTest",["#group-apiTest2","#group-apiTest3","#group-apiTest4"]]

Please try this code logic

String group1 = "#group-apiTest1";
JsonArray existingArray = ["#group-apiTest2","#group-apiTest3","#group-apiTest4"];
JsonArrayBuilder builder = Json.createArrayBuilder();
builder.add(group1);
existingArray.forEach(builder::add);
JsonObject jsonRequest = Json.createObjectBuilder()
                .add("tags", builder)
                .build();

Since you cannot directly add values to JsonArray you have to create a new builder and add your elements.

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

Comments

0

I can't see what's wrong.
But please try this:

JsonObject jsonRequest = Json.createObjectBuilder()
                        .add("tags", Json.createArrayBuilder(existingArray).add(0, group1))
                        .build();

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.