如何使用杰克逊将树json对象映射到List <>

时间:2018-10-01 20:52:29

标签: java json hibernate

执行查询后,结果将转换为JSON。格式如下:

[
    {
        "version": "1.0.1",
        "device.id": 1234,
        "user.id": 1234,
        "device.platform": "IOS",
        "lastActivity": null,
        "id": 987,
        "when": "2017-08-05",
        "device.platformVersion": "1.2.2",
        "endPointArn": "arn-here-123"
    },
    {
        "version": "1.0.2",
        "device.id": 2345,
        "user.id": 9876,
        "device.platform": "IOS",
        "lastActivity": null,
        "id": 753,
        "when": "2017-08-05",
        "device.platformVersion": "1.2.2",
        "endPointArn": "arn-here-123"
    }
]

我需要将此json映射为List <>对象,其中:

public class DeviceUser {
  private Integer id;
  private String version;
  private Date when;
  private String endPointArn;
  private Device device;
  private User user;
}

我们可以看到带有attrObject.fieldObject的键(例如:“ device.id”:2345),我看不到转换为预期格式的方法。 最终的格式为:

[
    {
        "version": "1.0.1",
        "user": {
            "id": 1234
        },
        "device": {
            "id": 1234,
            "platform": "IOS",
            "platformVersion": "1.2.2"
        },
        "lastActivity": null,
        "id": 987,
        "when": "2017-08-05",
        "endPointArn": "arn-here-123"
    },
    {
        "user": {
            "id": 9876
        },
        "device": {
            "id": 2345,
            "platform": "IOS",
            "platformVersion": "1.2.2"
        },
        "version": "1.0.2",
        "lastActivity": null,
        "id": 753,
        "when": "2017-08-05",
        "endPointArn": "arn-here-123"
    }
]

2 个答案:

答案 0 :(得分:2)

如果您使用的是Jackson,请尝试使用JsonPropety批注对字段(或getter / setter)进行批注。

赞:

@JsonProperty("device.id") private Device device;

答案 1 :(得分:0)

因此,我使用结果集上的新转换器解决了这种情况。转换器实际上只是迭代结果并搜索“。”。使用反射。我认为这是一个糟糕的策略。因此,我接受新的答案。

我使用的变压器是:AliasToBeanNestedResultTransformer