Reputation: 9411
I have a need to serialize a JSON without being attached to particular schema for resulting object, e.g., to some generic set/map/hashmap.
As input, I have a string with a JSON. I do not know schema for that JSON.
As output, I want a Java Object such as Hashmap or similar that has key-value serialization of input.
Note that input JSON has both basic fields and Array/List inside it.
I have to use Java and Jackson (or some other library). How I possibly can do that?
Upvotes: 3
Views: 2786
Reputation: 14328
Jackson data binding is able to read any json input into a Map with String key and Object value (that can be also a map or collection). You just tell the mapper that you would like to read the json into a map. You do that by giving the mapper the appropriate type reference:
import java.util.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test
{
public static void main(String[] args)
{
try {
String json = "{ "
+ "\"string-property\": \"string-value\", "
+ "\"int-property\": 1, "
+ "\"bool-property\": true, "
+ "\"collection-property\": [\"a\", \"b\", \"c\"], "
+ "\"map-property\": {\"inner-property\": \"inner-value\"} "
+ "}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
System.out.println("input: " + json);
System.out.println("output:");
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println("key: " + entry.getKey());
System.out.println("value type: " + entry.getValue().getClass());
System.out.println("value: " + entry.getValue().toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
output:
input: { "string-property": "string-value", "int-property": 1, "bool-property": true, "collection-property": ["a", "b", "c"], "map-property": {"inner-property": "inner-value"} }
output:
key: string-property
value type: class java.lang.String
value: string-value
key: int-property
value type: class java.lang.Integer
value: 1
key: bool-property
value type: class java.lang.Boolean
value: true
key: collection-property
value type: class java.util.ArrayList
value: [a, b, c]
key: map-property
value type: class java.util.LinkedHashMap
value: {inner-property=inner-value}
Upvotes: 3