fastjson icon indicating copy to clipboard operation
fastjson copied to clipboard

把json字符串反序列化成Map的错误。

Open bglmmz opened this issue 12 years ago • 2 comments

用的fastjons的版本是: 1.1.41

json字符串如下:

{
    "user_id": 5300, 
    "flag": 0, 
    "configs": [
        {
            "user_id": 5300, 
            "config_item_id": 1015, 
            "type": 0
        }, 
        {
            "user_id": 5300, 
            "config_item_id": 1016, 
            "type": 0
        }
    ]
}

反序列化代码如下:

HashMap jsonMap = JSON.parseObject(jsonData, HashMap.class);
List<HashMap> configDataList = (List<HashMap>)jsonMap.get("configs");
for(HashMap configData : configDataList ){//这行出错
    int roleId = (Integer)configData.get("type");
    System.out.println("config.type:" + roleId);
}

错误信息如下: Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to java.util.HashMap

请问,这种形式json数据,要反序列化成HashMap,该如何处理?

bglmmz avatar Oct 20 '14 07:10 bglmmz

Multiple markers at this line

- Type mismatch: cannot convert from element type Object to HashMap

- HashMap is a raw type. References to generic type HashMap<K,V> should be 

 parameterized

你这里 configDataList   List 中 类型与 HashMap不匹配,编译通不过的

[email protected]  发件人: bglmmz发送时间: 2014-10-20 15:26收件人: alibaba/fastjson主题: [fastjson] 把json字符串反序列化成Map的错误。 (#230)用的fastjons的版本是: 1.1.41 json字符串如下:

{

    "user_id": 5300, 

    "flag": 0, 

    "configs": [

        {

            "user_id": 5300, 

            "config_item_id": 1015, 

            "type": 0

        }, 

        {

            "user_id": 5300, 

            "config_item_id": 1016, 

            "type": 0

        }

    ]

}

反序列化代码如下:

HashMap jsonMap = JSON.parseObject(jsonData, HashMap.class);

List configDataList = (List)jsonMap.get("configs");

for(HashMap configData : configDataList ){//这行出错

    int roleId = (Integer)configData.get("type");

    System.out.println("config.type:" + roleId);

}

错误信息如下:

Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to java.util.HashMap 请问,这种形式json数据,要反序列化成HashMap,该如何处理? — Reply to this email directly or view it on GitHub.

nnstn avatar Nov 24 '14 14:11 nnstn

configData是JSONObject ,JSONObject 实现了map接口,里面包含一个map,所以你可以直接当作map来用,不用转HashMap的呀

mupengX avatar Nov 26 '14 01:11 mupengX