[英]How to write Java class to fetch the object from Json which doesn't have fixed fields?
I need to have Java class to accommodate below requirement and it should be compatible for Jackson's parsing using Object Mapper. 我需要具有Java类来满足以下要求,并且该类应与使用Object Mapper的Jackson解析兼容。
The Json is in below format : Json的格式如下:
[
{
"name" : "Snehal",
"property1" : "value11",
"property2" : "value12",
"property3" : "value13",
},
{
"name" : "Masne",
"property1" : "value21",
"property2" : "value22",
"property3" : "value23",
},
]
In above Json, the no. 在Json以上,没有。 of properties are not fixed, meaning there can be, say, property4, 5, 6, etc 属性的数量不是固定的,也就是说可以有property4、5、6等
The corresponding Java class could be thought of as below : 可以考虑以下对应的Java类:
Class MyClass
{
String name;
List<String> properties;
// getters, setters, etc
}
But this wont solve the purpose since, in this case, Json will generated something like of below format: 但这无法解决目的,因为在这种情况下,Json将生成类似以下格式的内容:
[
{
"name" : "Snehal",
[
{"property" : "value1" },
{"property" : "value1" },
{"property" : "value1" }
]
},
{
.... []
}
]
How do I implement the Java class to achieve the data in specifeid Json format ? 如何实现Java类以实现特定Json格式的数据?
You can use @JsonAnyGetter/@JsonAnySetter annotations to mark that your class has 'extra' properties in addition to the declared fields. 您可以使用@ JsonAnyGetter / @ JsonAnySetter批注来标记您的类除声明的字段外还具有“额外”属性。
Here is an example: 这是一个例子:
public class JacksonAnyGetter {
static final String JSON = " { \n" +
" \"name\" : \"Snehal\",\n" +
" \"property1\" : \"value11\",\n" +
" \"property2\" : \"value12\",\n" +
" \"property3\" : \"value13\"\n" +
"\n" +
" }";
static class Bean {
public String name; // we always have name
private Map<String, Object> properties = new HashMap<>();
@JsonAnySetter
public void add(String key, String value) {
properties.put(key, value);
}
@JsonAnyGetter
public Map<String, Object> getProperties() {
return properties;
}
@Override
public String toString() {
return "Bean{" +
"name='" + name + '\'' +
", properties=" + properties +
'}';
}
}
public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final Bean bean = mapper.readValue(JSON, Bean.class);
System.out.println(bean);
final String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean);
System.out.println(json);
}
}
Output: 输出:
Bean{name='Snehal', properties={property3=value13, property2=value12, property1=value11}}
{
"name" : "Snehal",
"property3" : "value13",
"property2" : "value12",
"property1" : "value11"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.