[英]Is there a way with Jackson ObjectMapper (without a custom @JsonCreator) to unmarshall this Json to the supplied Java Dto?
I have two Java classes: 我有两个Java类:
public class Request
{
private List<Item> subItems;
public Request()
{
}
public List<Item> getSubItems()
{
return subItems;
}
public void setSubItems(List<Item> subItems)
{
this.subItems = subItems;
}
}
class Item
{
private String name;
private String functionName;
//...elided...
}
The subItems
that will be passed can be complex (include a function) or simple (just a name). 该
subItems
将传递可以是复杂的(包括功能)或简单(只是一个名字)。 There can be a mix of these. 这些可以混合在一起。 To simplify the JSON, I'd like to be able to accept the following:
为了简化JSON,我希望能够接受以下内容:
JSON: JSON:
{
"subItems": [
{
"name": "complexType",
"function": "someFunction"
},
"simpleType"
]
}
and then have this turned into the equivalent of the following instance: 然后将其转换为以下实例的等效对象 :
Request request = new Request();
request.setSubItems(
Arrays.asList(
new Item( "complexType", "SomeFunction" ),
new Item( "simpleType" )
)
);
Is this possible with Jackson/ObjectMapper? Jackson / ObjectMapper有可能吗? What settings and annotations would I need?
我需要什么设置和注释?
If your Item
class has a string constructor, it will be called with the "simpleType"
value. 如果您的
Item
类具有字符串构造函数,则将使用"simpleType"
值对其进行调用。
class Item {
private String name;
private String functionName;
public Item() {
}
public Item(String name) {
this.name = name;
}
// getters and setters here
}
Full demo 完整演示
public class Request {
public static void main(String[] args) throws IOException {
String json = "{\"subItems\":[" +
"{\"name\":\"complexType\",\"functionName\":\"SomeFunction\"}," +
"\"simpleType\"" +
"]}";
Request request = new ObjectMapper().readValue(json, Request.class);
System.out.println(request);
}
private List<Item> subItems;
public Request() {
}
public Request(Item... subItems) {
this.subItems = Arrays.asList(subItems);
}
public List<Item> getSubItems() {
return this.subItems;
}
public void setSubItems(List<Item> subItems) {
this.subItems = subItems;
}
@Override
public String toString() {
return "Request [subItems=" + this.subItems + "]";
}
}
class Item {
private String name;
private String functionName;
public Item() {
}
public Item(String name) {
this.name = name;
}
public Item(String name, String functionName) {
this.name = name;
this.functionName = functionName;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getFunctionName() {
return this.functionName;
}
public void setFunctionName(String functionName) {
this.functionName = functionName;
}
@Override
public String toString() {
return "Item [name=" + this.name + ", functionName=" + this.functionName + "]";
}
}
Output 产量
Request [subItems=[Item [name=complexType, functionName=SomeFunction], Item [name=simpleType, functionName=null]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.