Reputation: 1213
I want to map an object to json to look like this:
{"MyClass" :
[
{"key" : "value"},
{"key" : "value"}
]}
However my code is giving me:
{"MyClass" : {
"list" : {
"key" : "value",
"key" : "value"
}
And my code is like this:
public class MyClass {
private List<Map<String,String>> list;
//getters & setters......
}
And:
Map<String, String> map1 = new HashMap<String,String>();
map1.put("key", "value");
Map<String,String> map2 = new HashMap<String,String>();
map2.put("key","value");
List<Map<String,String> list = new ArrayList<Map<String,String>();
list.add(map1);
list.add(map2);
And I am using ObjectMapper
to map the values. What can I do to get the layout I want?
Upvotes: 0
Views: 430
Reputation: 4973
using your code
class MyClass {
@JsonProperty("MyClass")
public List<Map<String,String>> list;
public static void main(String[] args) throws JsonProcessingException {
Map<String, String> map1 = new HashMap<String,String>();
map1.put("key", "value");
Map<String,String> map2 = new HashMap<String,String>();
map2.put("key","value");
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
list.add(map1);
list.add(map2);
MyClass d = new MyClass();
d.list = list;
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(d);
System.out.println(json);
}
}
output
{"MyClass":[{"key":"value"},{"key":"value"}]}
I used @JsonProperty
to change the name but you can also change the name of the var from list
to whatever
Note: this is just draft implementation... don't use public class vars, and such...
Upvotes: 1