我有一个名为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数组的属性。
答案 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());