【问题标题】:Skip level while deserialize with Gson使用 Gson 反序列化时跳过级别
【发布时间】:2020-10-20 15:42:49
【问题描述】:

大家好,我在使用 Gson 反序列化我的 json 时遇到了一些麻烦。 我通过一个简单的例子向你展示我的问题:

这是我收到的 JSON:

"order": {
    "id": "123",
    "name": "BOBI",
    "items": {
        "totalSize": 2,
        "records": [
            {
                "id": "456",
                "Quantity": 1.0,
                "Description": "Shipping",
                "TotalAmount": 6.29,
                "TotalTaxAmount": 0.3,
                "UnitPrice": 5.99
            }
        ]
    }
}

我想删除/跳过这个无用的部分:

        "totalSize": 2,
            "records": [

我需要一个类似 @SerializedName("items.records") 的功能来通过使用下面这样的 Java 类跳过一个级别:

public class SFOrderDto {
    
    private String id;
    
    private String name;
    
    @SerializedName("items.records")
    private List<SFProductDto> records;

}

主要调用:

SFOrderDto orderArray = gson.fromJson(jsonOrder, SFOrderDto.class);

希望有人可以帮助我,并为我的英语不好感到抱歉! :)

【问题讨论】:

标签: java json serialization gson


【解决方案1】:

我在这里找到了解决方案:Use jackson annotation JsonUnwrapped on a field with name different from its getter

添加@JsonUnwrapped 解决了我的问题。

public class SFOrderDto {
    
    private String id;
    
    private String name;
    
    @JsonUnwrapped
    @SerializedName("items.records")
    private List<SFProductDto> records;

}

感谢@papaya 和@Michal Ziober 试图帮助我:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 2017-01-27
    相关资源
    最近更新 更多