如何使用Json-Simple从JSON解析为Map并保留键顺序 [英] How to parse from JSON to Map with Json-Simple and retain key order

查看:891
本文介绍了如何使用Json-Simple从JSON解析为Map并保留键顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Json-Simple使用JSon-Simple lib编写配置文件,但是我在将json字符串转换为map时遇到了问题。

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.

调试我发现parse方法返回一个Map的对象!但是当我尝试直接转换为LinkedMap时,我得到一个ClassCastException:

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:

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


推荐答案

你不能只是将地图转换为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 {...}.

这篇关于如何使用Json-Simple从JSON解析为Map并保留键顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆