A. VA
A. VA

Reputation: 125

Can I use a for loop to build a JsonObject with Json.createObjectBuilder?

I'm trying to build a new JsonObject with some values from different existing JsonObjects. I want to store the names of the values in for example a separate file, string...

JsonObject object1 = ...;
JsonObject object2 = ...;
String [] names1 = { ... };
String [] names2 = { ... };

JsonObject newObject = Json.createObjectBuilder()
.add(names1[0], object1.getString(names1[0]))
.add(names1[1], object1.getString(names1[1]))
...
.add(names2[0], object2.getString(names2[0]))
.add(names2[1], object2.getString(names2[1]))
...
.build();

Can I instead add the names and values to the newObject using two foreach loops? This would allow me to change the names and fields that have to be added.

Upvotes: 0

Views: 650

Answers (2)

tevemadar
tevemadar

Reputation: 13225

Yes, you can do that, just keep the JsonObjectBuilder object:

JsonObject object1 = ...;
JsonObject object2 = ...;
String [] names1 = { ... };
String [] names2 = { ... };

JsonObjectBuilder builder = Json.createObjectBuilder();
for(String name: names1)
  builder.add(name, object1.getString(name));
for(String name: names2)
  builder.add(name, object2.getString(name));
JsonObject newObject = builder.build();

Upvotes: 2

Deepak Gunasekaran
Deepak Gunasekaran

Reputation: 757

Yes. You can iterate names1 and names2 variable's with two for loops and build the same logic you did here.

Upvotes: 0

Related Questions