[英]GSON: Convert JSON To Object with ignorance
I had JSON model for success some this 我有一些成功的JSON模型
{
data: {
.....
}
}
so I've create model: 所以我创建模型:
Class Model{
public Data data;
}
and I've used new Gson().fromJson(Model.class)
to convert in Object. 我使用了new Gson().fromJson(Model.class)
来转换为Object。 It works fine. 它工作正常。 Now my problem starts with when I get error in same API and its json Get changed 现在我的问题开始于我在相同的API中获得错误并且其json得到更改
{
message: {
.....
}
}
I want to use same model to be serialized in Json. 我想在Json中使用相同的模型进行序列化。
Class Model{
public Data data;
public Massage message;
}
But it gives me following Exception: Expected a string but was BEGIN_OBJECT at line 1 column 13
但它给了我以下异常: Expected a string but was BEGIN_OBJECT at line 1 column 13
Just configure and use ObjectMapper
from Jackson lib: 只需配置并使用Jackson lib中的ObjectMapper
:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
The mapper should be defined as 映射器应定义为
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Please see full Demo example 请参阅完整的演示示例
public class Demo {
public static void main(String[] args) throws IOException {
String jsonData = "{" +
" \"data\": {" +
" }" +
"}";
String jsonMessage = "{" +
" \"message\": {" +
" }" +
"}";
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Model modelData = mapper.readValue(jsonData, Model.class);
Model modelMessage = mapper.readValue(jsonMessage, Model.class);
System.out.println(modelData);
System.out.println(modelMessage);
}
}
class Model {
private Data data;
private Message message;
@Override
public String toString() {
return "Model{" +
"data=" + data +
", message=" + message +
'}';
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
private static class Data {}
private static class Message {}
}
BTW, ObjectMapper is Thread Safe, so you can define one constant to not create it each time when you read Json. 顺便说一句,ObjectMapper是线程安全的,所以你可以定义一个常量,以便每次读取Json时都不创建它。
More info you can find here: http://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/ObjectMapper.html 你可以在这里找到更多信息: http : //fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/ObjectMapper.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.