java 如何使用 Json-Simple 从 JSON 解析到 Map 并保留键顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12938442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse from JSON to Map with Json-Simple and retain key order
提问by rafuru
I'm using Json-Simple to write a config file using JSon-Simple lib, but I'm having problems converting the json string to map.
我正在使用 Json-Simple 使用 Json-Simple lib 编写配置文件,但在将 json 字符串转换为映射时遇到问题。
Debugging I have found that parse method returns an object that is a Map! but when I try to cast directly to a LinkedMap I get a ClassCastException:
调试我发现 parse 方法返回一个 Map 对象!但是当我尝试直接转换为 LinkedMap 时,我得到一个 ClassCastException:
String json = aceptaDefault();
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
LinkedHashMap map = (LinkedHashMap)obj;
回答by Tom McClure
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).
除非您知道底层对象实际上是 LinkedHashMap(或者是扩展 LinkedHashMap 的类的实例),否则您不能只是将 Map 强制转换为 LinkedHashMap。
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-Simple 可能在幕后使用 HashMap 并且故意不保留原始 JSON 中键的顺序。显然,这个决定是出于性能原因。
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.
但是,你很幸运!有一种解决方法 - 事实证明,您可以在解码(解析)JSON 时向解析器提供自定义 ContainerFactory。
http://code.google.com/p/json-simple/wiki/DecodingExamples#Example_4_-_Container_factory
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.
这应该保留原始 JSON 中的键顺序。
If you don't care about the key order, you don't need a LinkedHashMap and you probably just meant to do this:
如果您不关心键顺序,则不需要 LinkedHashMap 并且您可能只是打算这样做:
String json = aceptaDefault();
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
Map map = (Map)obj;
You still might get a ClassCastException, but only if the json is a list [...]
and not an object {...}
.
您仍然可能会收到 ClassCastException,但前提是 json 是 list[...]
而不是 object {...}
。