jdereg / json-io

Convert Java to JSON. Convert JSON to Java. Pretty print JSON. Java JSON serializer. Deep copy Java object graphs.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Map<String, Object> typed serialization broken for Integer

gunmiosb opened this issue · comments

Concerning Issue #119 #
Problem seems to still be there.
In JsonWriter.writeCollectionElement() only boolean, double and long are written as primitives. Int uses writeImpl and converts it to an object.

public static void main(String[] args) {
		HashMap<String,Object> map = new HashMap<>();
		map.put("int", 1);
		map.put("long", 2l);
		String json = JsonWriter.objectToJson(map);
		System.out.println(json);
}

Results in:
{"@type":"java.util.HashMap","int":{"@type":"int","value":1},"long":2}

Since the key (String value of 'int') in the Map is just a key and not a Java field, there is nothing specifying what the data type of the associated is. So the int value is written in Object form so that when it is reconstructed, it will be reconstructed as an 'int' and not a long.

This is by design. Hand-coded JSON, not written by the serializer, where you changed the value associated to the 'int' key as a value, would read into the Map, and would be instantiated as a long, as integer values in JSON are read into longs when the type is not known (to handle the full range).

If you write the JSON with options.put(JsonWriter.TYPE, false), then the 'int' will be written out like you expect. This may or may not be what you want with the rest of the object graph.