无法使用Map,ObjectMapper解析Json

时间:2012-11-06 06:22:03

标签: java json parsing collections object-object-mapping

现在有一天我有Json解析经验。没有多少收集练习。我有一个Json字符串

{   
    "time":1352113682,
    "api_version":"1",
    "firstname":"abc",
    "lastname":"xyz",
    "company":"Cool Apps",
    "email":"abc@apps.com.au"
}

我上课了

public class AuthenticateUser implements Serializable{

    // Response when Successfully Login
    public String time;
    public String api_version;
    public String firstname;
    public String lastname;
    public String company;
    public String email;

}

尝试像这样解析它

Map<String, AuthenticateUser> map=null;
ObjectMapper mapper=new ObjectMapper();
try{
    map=mapper.readValue(result,new TypeReference<Map<String, AuthenticateUser>>(){});
    Set<String> keys=map.keySet();
    for (String key : keys) {
    System.out.println(map.get(key).time);
    System.out.println(map.get(key).api_version);
        System.out.println(map.get(key).firstname);
    System.out.println(map.get(key).lastname);
    System.out.println(map.get(key).company);
    System.out.println(map.get(key).email);
    }
}catch (Exception e) {
    e.printStackTrace();
}

但是要犯这个错误

com.fasterxml.jackson.databind.JsonMappingException:无法从JSON整数中实例化类型[simple type,class AuthenticateUser]的值;没有single-int-arg构造函数/工厂方法     at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromInt(StdValueInstantiator.java:316)     在com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromNumber(BeanDeserializer.java:427)     在com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:119)     at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringMap(MapDeserializer.java:429)     在com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:310)     在com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:26)     at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2577)     at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:1817)     在Driver $ 1.run(Driver.java:140)

1 个答案:

答案 0 :(得分:0)

您在开头提供的示例是针对单个AuthenticateUser对象。是否所有这些都作为输入传递给该程序?这绝对不会妥善解析。

单个AuthenticateUser不是类型的Map(String,AuthenticateUser)

我想也许你很困惑,为什么要制作地图?如果您打算只解析一个对象,您只需要:

AuthenticateUser user =mapper.readValue(result, AuthenticateUser.class);

System.out.println(user.time);

这看起来怎么样?你在JSON传递地图吗?