如何将复杂的 JSON 反序列化为 java 对象
How to deserialize complex JSON to java object
我需要将 JSON 反序列化为 java class。
我有 JSON 如下所示:
{
"data": {
"text": "John"
},
"fields":[
{
"id": "testId",
"name": "fieldName",
"options": {
"color": "#000000",
"required": true
}
},
{
"id": "testId",
"name": "fieldName1",
"options": {
"color": "#000000",
"required": false
}
}
]
}
我需要将此 JSON(仅“字段”部分)反序列化为 java class,如下所示:
public class Field {
public final String id;
public final String name;
public final String color;
public final boolean required;
}
我需要得到如下内容:
// The key is the id from field object (it can be the same in the multiple objects.)
Map<String, List<Field>> fields = objectMapper.readValue(json, Map<String, List<Field>>);
如何使用 Jackson
来实现?
As long as jackson doesn't support @JsonWrapped
, you have to use the following work around.
首先您需要创建一个包含 fields
:
的自定义 class
public class Fields {
public List<Field> fields;
}
根据您的 ObjectMapper
配置,您必须将 @JsonIgnoreProperties(ignoreUnknown = true)
添加到 Fields
class,以忽略任何其他属性。
接下来就是要定义嵌套的Options
class,暂时单独使用:
public class Options {
public String color;
public boolean required;
}
最后将此构造函数添加到您的 Field
class:
@JsonCreator
public Field(@JsonProperty("id") String id, @JsonProperty("name") String name, @JsonProperty("options") Options options){
this.id = id;
this.name = name;
this.color = options.color;
this.required = options.required;
}
@JsonCreator
注释向 jackson 指示此构造函数需要用于反序列化。此外,@JsonProperty
注释是必需的,因为字节码中不保留构造函数和方法的参数
然后你可以像这样反序列化你的json:
List<Field> fields = objectMapper.readValue(json, Fields.class).fields;
我需要将 JSON 反序列化为 java class。
我有 JSON 如下所示:
{
"data": {
"text": "John"
},
"fields":[
{
"id": "testId",
"name": "fieldName",
"options": {
"color": "#000000",
"required": true
}
},
{
"id": "testId",
"name": "fieldName1",
"options": {
"color": "#000000",
"required": false
}
}
]
}
我需要将此 JSON(仅“字段”部分)反序列化为 java class,如下所示:
public class Field {
public final String id;
public final String name;
public final String color;
public final boolean required;
}
我需要得到如下内容:
// The key is the id from field object (it can be the same in the multiple objects.)
Map<String, List<Field>> fields = objectMapper.readValue(json, Map<String, List<Field>>);
如何使用 Jackson
来实现?
As long as jackson doesn't support
@JsonWrapped
, you have to use the following work around.
首先您需要创建一个包含 fields
:
public class Fields {
public List<Field> fields;
}
根据您的 ObjectMapper
配置,您必须将 @JsonIgnoreProperties(ignoreUnknown = true)
添加到 Fields
class,以忽略任何其他属性。
接下来就是要定义嵌套的Options
class,暂时单独使用:
public class Options {
public String color;
public boolean required;
}
最后将此构造函数添加到您的 Field
class:
@JsonCreator
public Field(@JsonProperty("id") String id, @JsonProperty("name") String name, @JsonProperty("options") Options options){
this.id = id;
this.name = name;
this.color = options.color;
this.required = options.required;
}
@JsonCreator
注释向 jackson 指示此构造函数需要用于反序列化。此外,@JsonProperty
注释是必需的,因为字节码中不保留构造函数和方法的参数
然后你可以像这样反序列化你的json:
List<Field> fields = objectMapper.readValue(json, Fields.class).fields;