Jackson将json字符串序列化为Java对象 [英] Jackson double serialized json string to Java object
本文介绍了Jackson将json字符串序列化为Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Json字符串,它有一个字符串消息字段。
字符串:
I have a Json string which has a string message field. String:
{ "Type" : "Text",
"Subject" : "data received",
"Message" :"{\\"language\\":\\"US\\",\\"data\\":\\"signature\\"}"
}
我想转换它进入以下结构:
Notification.java
I want to convert it into the following structure: Notification.java
public class Notification {
String type;
String subject;
Message message;
}
Message.java
Message.java
public class Message {
String language;
String data;
}
有没有办法可以直接将字符串转换为Java对象以上结构?我想避免反序列化两次。
Is there a way in which I can directly convert the string to a Java object of the above structure? I want to avoid deserializing twice.
推荐答案
您可以创建自定义反序列化器
将消息
文本反序列化为消息
对象并注释消息
带的类@JsonDeserialize
:
You can create a custom Deserializer
to deserialize the Message
text into Message
object and annotate the Message
class with @JsonDeserialize
:
@JsonDeserialize(using = MessageDeserializer.class)
public class Message {
String language;
String data;
}
public class MessageDeserializer extends JsonDeserializer<Message> {
public MessageDeserializer() {
super();
}
@Override
public Message deserialize(
final JsonParser jsonParser, final DeserializationContext deserializationContext) throws
IOException, JsonProcessingException {
final String messageText = jsonParser.getText();
// parse messageText into Message object
}
}
这篇关于Jackson将json字符串序列化为Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文