Reputation: 13367
How can I map the following json payload to a more friendly dictionary like look up? The data I get back is coming back as generic key values in a list. But I want to be able to access everything as a dictionary lookup by the key instead of storing everything as a list.
[
{
"key":"value1",
"values":[
10.5
]
},
{
"key":"value2",
"values":[
20.5
]
}
o o o more values here... o o o
]
This is what I have for object to map but I want to map by key to automatically building a hashmap or dictionary withough having to iterate thought the list.
class keyValPairObject {
private String key;
private List<?> values;
}
class mainMapper {
List<keyValPairObject> theKeyValPairValues;
}
I'd like to store it in an object where I can access it like:
theKeyValPairValues["values1"].values;
Upvotes: 1
Views: 276
Reputation: 1322
Okay I hope this helps you. Here is some code:
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
public String hashmapToJson() {
ObjectMapper mapper = new ObjectMapper();
String result = "";
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
String key1 = "values1";
String key2 = "values2";
String key3 = "values3";
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
List<String> list3 = new ArrayList<String>();
for(int i = 0; i < 3; i++){
list1.add("Element" + i);
list2.add("Element" + i);
list3.add("Element" + i);
}
map.put(key1, list1);
map.put(key2, list2);
map.put(key3, list3);
try {
result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
This will return:
{
"values1":["Element0","Element1","Element2"],
"values2":["Element0","Element1","Element2"],
"values3":["Element0","Element1","Element2"]
}
Is this what you were looking for?
Upvotes: 1
Reputation: 116620
Perhaps you should use "Tree Models", so that:
JsonNode root = mapper.readTree(jsonSource);
and then you can traverse values using "get()" and "path()" methods. path()
is nice since you can skip any null checks (if a node does not exist, a virtual "missing" node is included, so you can freely chain calls).
That way you would do like:
int value = rootNode.path(0).path("value").path(0).asIntValue();
to get that 10.5
value from your structure.
Bit more info can be found from this entry and from "Tree Model" of databind project's readme.
Upvotes: 1