Issue
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");
Solution
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"
}
Answered By - Raymond Choi
Answer Checked By - Willingham (JavaFixing Volunteer)