自定义Jackson Deserializer来处理任何bean的属性

时间:2015-04-30 06:32:43

标签: java json jackson

我有一个名为Channel的班级,其roles属性如下

public class Channel{
   private int id;
   private String roles;
}

我的客户端JSON是

{
 "id":"12345787654323468",
 "roles":[
          {"name":"admin","permissions":["can publish","can reject"]},
          {"name":"moderator","permissions":["can publish","can reject"]}
         ]
}

但是当我将这个JSON转换为Channel对象时,我遇到了异常

com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token
 at [Source: java.io.StringReader@6d25f91; line: 1, column: 253] (through reference chain: com.pokuri.entity.Channel["roles"])

现在我想将其反序列化为roles类的属性Channel中的字符串。我也可以编写单个自定义反序列化器来处理任何bean中JSON数组的属性。

1 个答案:

答案 0 :(得分:3)

自定义反序列化器可以在这里完成。 :

class CustomDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {

        JsonNode node = jsonParser.readValueAsTree();       
        return node.toString();
    }

}

现在要在你的bean中使用它,你必须将它包含在roles字段:

class Channel {
    private long id;

    @JsonDeserialize(using = CustomDeserializer.class)
    private String roles;



    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getRoles() {
        return roles;
    }

    public void setRoles(String roles) {
        this.roles = roles;
    }

}

注意:我将id的值视为long,因为它显示int的错误,因为id中的值过大} attribute。

现在,ObjectMapper可以轻松地将您的JSON反序列化为Channel类:

String json = "{\"id\":\"12345787654323468\",\"roles\":[{\"name\":\"admin\",\"permissions\":[\"can publish\",\"can reject\"]},{\"name\":\"moderator\",\"permissions\":[\"can publish\",\"can reject\"]}]}";

ObjectMapper mapper = new ObjectMapper();
Channel channel = mapper.readValue(json, Channel.class);

System.out.println("Roles :"+channel.getRoles());