简体   繁体   中英

How to create a JSON with unknown number of fields?

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");
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"
}

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM