Java – how to use JSON simple to parse from JSON to map and preserve the key order
I'm using JSON simple and JSON simple lib to write configuration files, but I'm having trouble converting JSON strings to maps
Debugging, I found that the parse method returns a map object! But when I try to convert directly to linkedmap, I get a ClassCastException:
String json = aceptaDefault(); JSONParser parser = new JSONParser(); Object obj = parser.parse(json); LinkedHashMap map = (LinkedHashMap)obj;
Solution
Unless you know that the underlying object is actually a LinkedHashMap (or an instance of a class that extends LinkedHashMap), you cannot convert a map to a LinkedHashMap
JSON - simple may use HashMap by default, deliberately not keeping the order of keys in the original JSON Obviously, this decision is for performance reasons
But you're lucky! One solution – it turns out that when you decode (parse) JSON, you can provide the parser with a custom containerfactory
http://code.google.com/p/json-simple/wiki/DecodingExamples#Example_4_ -_ Container_ factory
String json = aceptaDefault(); JSONParser parser = new JSONParser(); ContainerFactory orderedKeyFactory = new ContainerFactory() { public List creatArrayContainer() { return new LinkedList(); } public Map createObjectContainer() { return new LinkedHashMap(); } }; Object obj = parser.parse(json,orderedKeyFactory); LinkedHashMap map = (LinkedHashMap)obj;
This should preserve the key order in the original JSON
If you don't care about key order, you don't need LinkedHashMap. You may just want to do this:
String json = aceptaDefault(); JSONParser parser = new JSONParser(); Object obj = parser.parse(json); Map map = (Map)obj;
You may still get a ClassCastException, but the premise is that JSON is a list rather than an object {...}