Home > Software design >  How to create a JSON with unknown number of fields?
How to create a JSON with unknown number of fields?

Time:08-24

I need to convert a structure like this:

List<String> fields;

to JSON like this:

{
   "field1": "data1",
   "field2": "data2",
   "field3": "data3",
   ...
}

How can I do this?

UPD: List contains values, like this:

List<String> fields = List.of("data1", "data2", "data3");

CodePudding user response:

ObjectNode objectNode = new ObjectMapper().createObjectNode();
List<String> fields = new ArrayList<>();
fields.add("data1");
fields.add("data2");
fields.add("data3");
for (int i = 0; i < fields.size(); i  ) {
    objectNode.put("field"   (i 1), fields.get(i));
}
System.out.println(objectNode.toPrettyString());

Output

{
  "field1" : "data1",
  "field2" : "data2",
  "field3" : "data3"
}

CodePudding user response:

you can use map collection Map<String,Object> :

Map<String,Object> mapp = new HashMap<>();
mapp.put("field1", "data1");
mapp.put("field2", "data2");
mapp.put("field3", "data3");
mapp.put("field4", "data4");
JSONObject json = new JSONObject(mapp);
System.out.println(json);

output:

{
  "field1":"data1",
  "field3":"data3",
  "field2":"data2",
  "field4":"data4"
}
  • Related