使用Spring Boot和Jackson,如何将包装/内部列表反序列化为直接在外部级别的列表?
例如,我有:
{ "transaction": { "items": { "item": [ { "itemNumber": "193487654", "itemDescription": "Widget", "itemPrice": "599.00", "itemQuantity": "1", "itemBrandName": "ACME", "itemCategory": "Electronics", "itemTax": "12.95" }, { "itemNumber": "193487654", "itemDescription": "Widget", "itemPrice": "599.00", "itemQuantity": "1", "itemBrandName": "ACME", "itemCategory": "Electronics", "itemTax": "12.95" } ] }, ... } }
在JSON中,item是items; 下的列表。但我想将其解析为items直接位于下方的名为列表的列表transaction,而不是定义Items包含名为的列表的DTO item。
item
items
transaction
Items
这可能吗?如何定义此DTO Item?
Item
public class TrasactionDTO { private List<Item> items; ... } public class Item { }
看来这@JsonUnwrapped就是我所需要的。
@JsonUnwrapped
https://www.baeldung.com/jackson- annotations
@JsonUnwrapped 定义在序列化/反序列化时应该解包/展平的值。 让我们确切地了解它是如何工作的。我们将使用注释解开属性名称: public class UnwrappedUser { public int id; @JsonUnwrapped public Name name; public static class Name { public String firstName; public String lastName; } } 现在让我们序列化此类的实例: @Test public void whenSerializingUsingJsonUnwrapped_thenCorrect() throws JsonProcessingException, ParseException { UnwrappedUser.Name name = new UnwrappedUser.Name("John", "Doe"); UnwrappedUser user = new UnwrappedUser(1, name); String result = new ObjectMapper().writeValueAsString(user); assertThat(result, containsString("John")); assertThat(result, not(containsString("name"))); } 输出是这样的-静态嵌套类的字段与其他字段一起展开: { "id":1, "firstName":"John", "lastName":"Doe" }
@JsonUnwrapped 定义在序列化/反序列化时应该解包/展平的值。
让我们确切地了解它是如何工作的。我们将使用注释解开属性名称:
public class UnwrappedUser { public int id; @JsonUnwrapped public Name name; public static class Name { public String firstName; public String lastName; } }
现在让我们序列化此类的实例:
@Test public void whenSerializingUsingJsonUnwrapped_thenCorrect() throws JsonProcessingException, ParseException { UnwrappedUser.Name name = new UnwrappedUser.Name("John", "Doe"); UnwrappedUser user = new UnwrappedUser(1, name); String result = new ObjectMapper().writeValueAsString(user); assertThat(result, containsString("John")); assertThat(result, not(containsString("name"))); }
输出是这样的-静态嵌套类的字段与其他字段一起展开:
{ "id":1, "firstName":"John", "lastName":"Doe" }
因此,它应该类似于:
public class TrasactionDTO { private List<Item> items; ... } public static class Item { @JsonUnwrapped private InnerItem innerItem; ... } public static class InnerItem { private String itemNumber; ... }