且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Json-Simple从JSON解析为Map并保留键顺序

更新时间:2023-11-30 23:42:34

你不能只是将地图转换为LinkedHashMap除非你知道底层对象实际上是一个LinkedHashMap(或者是一个扩展LinkedHashMap的类的实例)。

You can't just cast a Map to a LinkedHashMap unless you know the underlying object is actually a LinkedHashMap (or is an instance of a class that extends LinkedHashMap).

JSON-Simple默认情况下可能在引擎盖下使用HashMap故意不保留原始JSON中键的顺序。显然这个决定是出于性能原因。

JSON-Simple by default probably uses a HashMap under the hood and intentionally does not preserve the order of the keys in the original JSON. Apparently this decision was for performance reasons.

但是,你很幸运!有一种解决方法 - 事实证明,在解码(解析)JSON时,您可以为解析器提供自定义ContainerFactory。

But, you're in luck! There is a way around this - it turns out, you can supply a custom ContainerFactory to the parser when decoding (parsing) the JSON.

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;

这应该保留原始JSON中的键顺序。

This should preserve the key order in the original JSON.

如果你不关心键盘顺序,你不需要LinkedHashMap,你可能只是想这样做:

If you don't care about the key order, you don't need a LinkedHashMap and you probably just meant to do this:

String json = aceptaDefault();
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);  
Map map = (Map)obj;

你仍然可能得到一个ClassCastException,但前提是json是一个列表 [...] 而不是对象 {...}

You still might get a ClassCastException, but only if the json is a list [...] and not an object {...}.