You need to use Object as Map value because it could be another Map, List or primitive (String, Integer, etc.). Jackson allows also to manipulate JSON using JsonNode types. We need to traverse JSON object but also JSON array (you forgot about it). In that case we need to:
- Deserialise
JSONtoJsonNode. - Traverse it using
JsonNodeAPI. - Convert to the
Map
Simple implementation:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class JsonApp {
public static void main(String[] args) throws Exception {
String json = "{\"Key1\": \"value1\", \"Key2\": { \"Key2.1\": \"value2.1\" }, \"Key3\":[{\"pRiMe\":11}]}";
Map<String, Object> map = convertJsonStringToMap(json);
System.out.println(map);
}
private static Map<String, Object> convertJsonStringToMap(String json) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
transformKeys(node);
TypeReference mapType = new TypeReference<Map<String, Object>>() {
};
return mapper.convertValue(node, mapType);
}
private static void transformKeys(JsonNode parent) {
if (parent.isObject()) {
ObjectNode node = (ObjectNode) parent;
List<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
names.forEach(name -> {
JsonNode item = node.remove(name);
transformKeys(item);
node.replace(name.toLowerCase(), item);
});
} else if (parent.isArray()) {
ArrayNode array = (ArrayNode) parent;
array.elements().forEachRemaining(JsonApp::transformKeys);
}
}
}
Above code prints:
{key1=value1, key2={key2.1=value2.1}, key3=[{prime=11}]}
We got rid of unsafe casting and our implementation is more concise.
Answer from Michał Ziober on Stack Overflow[Update Sept 2020] Although my original answer here, from many years ago, seems to be helpful and is still getting upvotes, I now use the GSON library from Google, which I find to be more intuitive.
I've got the following code:
public void testJackson() throws IOException {
ObjectMapper mapper = new ObjectMapper();
File from = new File("albumnList.txt");
TypeReference<HashMap<String,Object>> typeRef
= new TypeReference<HashMap<String,Object>>() {};
HashMap<String,Object> o = mapper.readValue(from, typeRef);
System.out.println("Got " + o);
}
It's reading from a file, but mapper.readValue() will also accept an InputStream and you can obtain an InputStream from a string by using the following:
new ByteArrayInputStream(astring.getBytes("UTF-8"));
There's a bit more explanation about the mapper on my blog.
Try TypeFactory. Here's the code for Jackson JSON (2.8.4).
Map<String, String> result;
ObjectMapper mapper;
TypeFactory factory;
MapType type;
factory = TypeFactory.defaultInstance();
type = factory.constructMapType(HashMap.class, String.class, String.class);
mapper = new ObjectMapper();
result = mapper.readValue(data, type);
Here's the code for an older version of Jackson JSON.
Map<String, String> result = new ObjectMapper().readValue(
data, TypeFactory.mapType(HashMap.class, String.class, String.class));
The reason what you've shown is unsafe is that with this assignment:
Class<T> type = typeMap.get(key);
T does not need to have anything to do with the Class retrieved from the map. T is always inferred from the surrounding context of the call to get. For example I can do this sequence of calls:
// T is inferred from the arguments as String (which is fine)
example.put("k", "v");
// T is inferred from the return value target type as Integer
Integer i = example.get("k");
Inside the get method, String.class is correctly retrieved from the type map, but an unchecked conversion is made to Class<Integer>. The call to type.cast(...) doesn't throw, because the value retrieved from the data map is a String. An implicit checked cast then actually happens to the return value, casting it to Integer and a ClassCastException is thrown.
This strange interaction is due to type erasure.
So, when we are storing multiple types in a single data structure, there are a number of ways to approach it, depending on what our needs are.
1. We can forego compilation checks if there is no way to perform them.
Storing the Class is pointless for the most part here because, as I showed above, it doesn't perform a useful validation. So we could redesign the map along the following lines:
class Example {
private final Map<String, Object> m = new HashMap<>();
void put(String k, Object v) {
m.put(k, v);
}
Object getExplicit(String k) {
return m.get(k);
}
@SuppressWarnings("unchecked")
<T> T getImplicit(String k) {
return (T) m.get(k);
}
}
getExplicit and getImplicit do a similar thing but:
String a = (String) example.getExplicit("k");
// the generic version allows an implicit cast to be made
// (this is essentially what you're already doing)
String b = example.getImplicit("k");
In both cases we're just relying on our own awareness as a programmer to not make mistakes.
Suppressing warnings isn't necessarily bad, it's just important to understand what they actually mean and what the implications are.
2. Pass a Class to get so the return value must be valid.
This is the way I've seen it done typically.
class Example {
private final Map<String, Object> m = new HashMap<>();
void put(String k, Object v) {
m.put(k, v);
}
<T> T get(String k, Class<T> c) {
Object v = m.get(k);
return c.isInstance(v) ? c.cast(v) : null;
}
}
example.put("k", "v");
// returns "v"
String s = example.get("k", String.class);
// returns null
Double d = example.get("k", Double.class);
But, of course, it means we need to pass two parameters to get.
3. Parameterize the keys.
This is a novel but more advanced and it may or may not be more convenient.
class Example {
private final Map<Key<?>, Object> m = new HashMap<>();
<V> Key<V> put(String s, V v) {
Key<V> k = new Key<>(s, v);
put(k, v);
return k;
}
<V> void put(Key<V> k, V v) {
m.put(k, v);
}
<V> V get(Key<V> k) {
Object v = m.get(k);
return k.c.isInstance(v) ? k.c.cast(v) : null;
}
static final class Key<V> {
private final String k;
private final Class<? extends V> c;
@SuppressWarnings("unchecked")
Key(String k, V v) {
// this cast will always be safe unless
// the outside world is doing something fishy
// like using raw types
this(k, (Class<? extends V>) v.getClass());
}
Key(String k, Class<? extends V> c) {
this.k = k;
this.c = c;
}
@Override
public int hashCode() {
return k.hashCode();
}
@Override
public boolean equals(Object o) {
return (o instanceof Key<?>) && ((Key<?>) o).k.equals(k);
}
}
}
So e.g.:
Key<Float> k = example.put("k", 1.0f);
// returns 1.0f
Float f = example.get(k);
// returns null
Double d = example.get(new Key<>("k", Double.class));
This might make sense if the entries are known or predictable so we can have something like:
final class Keys {
private Keys() {}
static final Key<Foo> FOO = new Key<>("foo", Foo.class);
static final Key<Bar> BAR = new Key<>("bar", Bar.class);
}
Then we don't have to construct a key object any time a retrieval is done. This works very well especially for adding some strong typing to stringly-typed scenarios.
Foo foo = example.get(Keys.FOO);
4. Don't have a map any kind of object can be put in, use polymorphism of some kind.
When possible and not too cumbersome, it's a good option. If there is a common behavior that the different types are used for, make it an interface or superclass so we don't have to use casting.
A simple example might be like this:
// bunch of stuff
Map<String, Object> map = ...;
// store some data
map.put("abc", 123L);
map.put("def", 456D);
// wait awhile
awhile();
// some time later, consume the data
// being particular about types
consumeLong((Long) map.remove("abc"));
consumeDouble((Double) map.remove("def"));
And we could instead substitute something like this:
Map<String, Runnable> map = ...;
// store operations as well as data
// while we know what the types are
map.put("abc", () -> consumeLong(123L));
map.put("def", () -> consumeDouble(456D));
awhile();
// consume, but no longer particular about types
map.remove("abc").run();
map.remove("def").run();
You are attempting to assign an element of type Class to a variable of type Class<T>. Of course that's an unchecked assignment. You seem to be implementing a heterogeneous map. Java (and any other strongly-typed language) has no way to express the value type of your map in a statically-type-safe way.
That is because the element types are only known at runtime. Expecting the compiler to statically type-check things that are not yet known is asking too much of it. The compiler can't even do reasonable static type inference, so expecting it to predict the future for dynamic type inference is really a stretch.
You need to give it concrete classes and not interfaces. So
List<Map<String, MyObject>> myObjects = mapper.readValue(json, new TypeReference<ArrayList<HashMap<String, MyObject>>>() {
});
What you need is to use @JsonTypeInfo annotation on type (class), which will include additional type information. In your case it looks as if you wanted to include a type id as property key.
If so, inclusion method should be "as wrapper object", and you will also need to define what type id of "myobject" binds to -- this can be done by adding @JsonTypeName("myobject") for MyObject class (it needs to be included in subtype of whatever has @JsonTypeInfo, but in this case both would be added for the same class).