Working with Jackson to convert nested JSON to Map - java

I'm currently using com.fasterxml.jackson.databind.ObjectMapper to take a JSON string and convert to a map. I'm struggling though to figure out how to work with my particular JSON input though and then how to Parse the output. The JSON I'm playing around with looks like this:
{
"data":[
{
"DATA.HELLO":[
{
"do_something":"true"
}
],
"DATA.GOODBYE":[
{
"do_something":"false"
}
]
}
]
}
Below is a snippet of my code. Ultimately I want something like a Map<String, Map> where I can grab "do_something" or whatever other attribute from "data.hello" or "data.goodbye".
So I can do something like map.get("data") to get the array, but I'm not sure how to grab - for example - the DATA.HELLO piece. I'm also not sure if what I'm doing here is the best way to handle this as this is the first time I've worked with Jackson and I'm fairly new to Java. Am I on the completely wrong track here?
String data = "{\"data\":[{\"DATA.HELLO\":[{\"do_something\":\"true\"}],\"DATA.GOODBYE\":[{\"do_something\":\"true\"}]}]}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Map> map = mapper.readValue(data, Map.class);
System.out.println(data);

Related

Serialize to JSON as name-value from String by Jackson ObjectMapper

I have some String, like:
String value = "123";
And when i serialize this string to json via ObjectMapper:
objectMapper.writeValueAsString(value);
Output is:
"123"
Is it possible to write String using either string name and string value? Desired output:
"value" : "123"
PS: i dont want to create DTO object with one field for serializing one String value.
you can also use the Jackson JsonGenerator
try (JsonGenerator generator = new JsonFactory().createGenerator(writer)) {
generator.writeStartObject();
generator.writeFieldName("value");
generator.writeString("123");
generator.writeEndObject();
}
}
If you have a plain string you'll get out a plain string when serialised. If you want to wrap it in an object then use a map for the simplest solution.
String value = "123";
Map<String, String> obj = new HashMap<>();
obj.put("value", value);
Passing that through the mapper will produce something like this:
{ "value": "123" }
If you change the map to <String, Object> you can pass in pretty much anything you want, even maps within maps and they'll serialise correctly.
If you really can't have the enclosing curly braces you can always take the substring but that would be a very weird use case if you're still serialising to JSON.
Create a Map:
Map<String, String> map = new HashMap<>();
map.put("value", value);
String parsedValue = ObjectMapper.writeValueAsString(map);
and you will get: {"value":"123"}
If you are using java 8 and want to do it in automated way without creating maps or manually putting string variable name "value", this is the link you need to follow-

How to parse the given string to map of string of map of string of object?

Hi my input string look like this
{
6138249={
value=[multi2, multi3, multi4],
key=TestMulticat
},
6161782={
value=Traps (Bamboo / Box),
key=Observation gear
}
}
I want to map this input string in Map<String,Map<String,Object>> in java.
As the input look more mysterious to me, i am not able to figure out the way to do the same.
I tried ObjectMapper class from jackson but still not able to map. The code i write look like this
Map<String,Map<String,Object>> data=objectMapper.readValue(singledoc, Map.class);
Can somebody suggest me either approach to do this or solution, both will be equally helpful.
Your input doesn't look like valid json, as it has unquoted string values.
Json would look like this:
{
6138249:{
value:["multi2", "multi3", "multi4"],
key:"TestMulticat"
},
6161782:{
value="Traps (Bamboo / Box)",
key="Observation gear"
}
}
For such input you can use jackson:
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
Map<String, Map<String, Object>> result = objectMapper
.readValue(test, new TypeReference<Map<String, Map<String, Object>>>() {});
ALLOW_UNQUOTED_FIELD_NAMES will help you to deal with unquoted field names, however there is no such option for unqouted values.
In your case as its not a json, you can either fix your serialization to produce valid jackson or write your own Deserializer for jackson handling this, because currently its not possible to read json with unquoted string values.

Parsing dynamic JSON values to Java objects

In my application I have lot of overviews (tables) with sorting and filtering capabilities. And becuase the different column can hold different value type (strings, numbers, dates, sets, etc.) the filter for these columns also can bring different values. Let me show you few examples (converted to JSON already as is sent to server via REST request):
For simple string value it is like:
{"<column_name>":"<value>"}
For number and date column the filter looks like:
{"<column_name>":[{"operator":"eq","value":"<value>"}]}
{"<column_name>":[{"operator":"eq","value":"<value1>"},{"operator":"gt","value":"<value2>"}]}
For set the filter looks like
{"<column_name>":["<value1>","<value2>"(,...)]}
Now I need to parse that JSON within a helper class that will build the WHERE clause of SQL query. In PHP this is not a problem as I can call json_decode and then simply check whether some value is array, string or whatever else... But how to do this simply in Java?
So far I am using Spring's JsonJsonParser (I didn't find any visible difference between different parsers coming with Spring like Jackson, Gson and others).
I was thinking about creating an own data object class with three different constructors or having three data object classes for all of the three possibilities, but yet I have no clue how to deal with the value returned for column_name after the JSON is parsed by parser...
Simply looking on the examples it gives me three possibilities:
Map<String, String>
Map<String, Map<String, String>>
Map<String, String[]>
Any idea or clue?
Jackson's ObjectMapper treeToValue should be able to help you.
http://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/ObjectMapper.html#treeToValue%28com.fasterxml.jackson.core.TreeNode,%20java.lang.Class%29
Your main problem is that the first version of you JSON is not the same construction than the two others. Picking the two others you could deserialize your JSON into a Map<String, Map<String, String> as you said but the first version fits a Map.
There are a couple solutions available to you :
You change the JSON format to always match the Map<String, Map<String, String> pattern
You first parse the JSON into a JsonNode, check the type of the value and deserialize the whole thing into the proper Map pattern.
(quick and dirty) You don't change the JSON, but you try with one of the Map patterns, catch JsonProcessingException, then retry with the other Map pattern
You'll have to check the type of the values in runtime. You can work with a Map<String, Object> or with JsonNode.
Map<String, Object>
JsonParser parser = JsonParserFactory.getJsonParser();
Map<String, Object> map = parser.parseMap(str);
Object filterValue = filter.get("<column_name>");
if (filterValue instanceof String) {
// str is like "{\"<column_name>\":\"<value>\"}"
} else if (filterValue instanceof Collection) {
for (Object arrayValue : (Collection<Object>) filterValue) {
if (arrayValue instanceof String) {
// str is like "{\"<column_name>\":[\"<value1>\",\"<value2>\"]}"
} else if (arrayValue instanceof Map) {
// str is like "{\"<column_name>\":[{\"operator\":\"eq\",\"value\":\"<value>\"}]}"
}
}
}
JsonNode
ObjectMapper mapper = new ObjectMapper();
JsonNode filter = mapper.readTree(str);
JsonNode filterValue = filter.get("<column_name>");
if (filterValue.isTextual()) {
// str is like "{\"<column_name>\":\"<value>\"}"
} else if (filterValue.isArray()) {
for (JsonNode arrayValue : filterValue.elements()) {
if (arrayValue.isTextual()) {
// str is like "{\"<column_name>\":[\"<value1>\",\"<value2>\"]}"
} else if (arrayValue.isObject()) {
// str is like "{\"<column_name>\":[{\"operator\":\"eq\",\"value\":\"<value>\"}]}"
}
}
}

How do you deal with arrays that are written like objects in gson?

I'm writing a client for an API that gives me JSON data in this way:
"Thing": {
"0": {
...
},
"1": {
...
},
"2": {
...
}
}
Because I'm attempting to put this in a List, I'm getting the error:
Expected BEGIN_ARRAY but was BEGIN_OBJECT
I don't want to have to add a HashMap to my Java object, I'd like to figure out a way to get gson to convert it properly. Is there a way to do this?
Thanks!
You can put the object in an HashMap and after you can convert this to a List:
HashMap<Integer, String> yourMapFromJSON = new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
List<String> list = new ArrayList<String>(yourMapFromJSON.values());
In case your model contain array instead of Map you haw two options.
parse the JSON into Map, and then retrieve the values from it.
create a specific parser for this case.

Can't parse JSON array of arrays to LinkedHashMap in Jackson

I' m developing an Android REST client. We use JSON as data exchange format, so I use a Jackson parser. I get different Json responses from the server like simple arrays:
{"user_id":"332","user_role":"1"}
or something else. All these stuff I parse to LinkedHashMap<String, Object> and everything works perfectly but when I got this response from the server:
[ { "user_id":"352",
"user_role":"expert",
"name":"Test 12-18",
"description":"Test" },
{ "user_id":"263",
"user_role":"novice lab",
"name":"Tom's Desk",
"description":"Desk"}
]
I got null: {} after parsing.Here is my code where i use Jackson:
ObjectMapper mapParametersToJSON = new ObjectMapper();
String serverResponseBody = responseFromServer.getBody();
LinkedHashMap<String, Object> resultofOperation = new LinkedHashMap<String,
Object>();
TypeReference<LinkedHashMap<String,Object>> genericTypeReferenceInformation = new
TypeReference<LinkedHashMap<String,Object>>() {};
try {
resultofOperation = mapParametersToJSON.readValue(serverResponseBody,
genericTypeReferenceInformation);
So, why Jackson failed to parse this? How can I fix this?
Others have suggested the problem, but solutions are bit incomplete. If you need to deal with JSON Objects and Arrays, you can either bind to java.lang.Object, check the type:
Object stuff = objectMapper.readValue(json, Object.class);
and you will get either List or Map (specifically, ArrayList or LinkedHashMap, by default; these defaults can be changed).
Or you can do JSON trees with JsonNode:
JsonNode root = objectMapper.readTree(json);
if (root.isObject()) { // JSON Object
} else if (root.isArray()) { ...
}
latter is often more convenient.
One nice thing is that you can still create regular POJOs out of these, for example:
if (root.isObject()) {
MyObject ob = objectMapper.treeToValue(MyObject.class);
}
// or with Object, use objectMapper.convertValue(ob, MyObject.class)
so you can even have different handling for different types; go back and forth different representations.
The first JSON in your question is a map, or an object. The second is an array. You're not parsing an array, you're parsing a map.
You need to do something like this:
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
Almost identical question with answer here.
In JSON the {"key": "value"} is Object and the ["this", "that"] is Array.
So, in case when you're receiving the array of objects you should use something like List<Map<Key, Value>>.
You are facing an error, because [] construction can't be translated into Map reference, only in List or array.
I would recommend do it something in this way:
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String,String>> parsedResult = objectMapper.reader(CollectionType.construct(LinkedList.class, MapType.construct(LinkedHashMap.class, SimpleType.construct(String.class), SimpleType.construct(String.class)))).readValue(serverResponseBody);
//if you need the one result map
Map<String, String> resultMap = new LinkedHashMap<String, String>();
for (Map<String, String> map: parsedResult){
resultMap.putAll(map);
}

Categories