【问题标题】:json parsing with resttemplate用resttemplate解析json
【发布时间】:2016-09-02 23:48:43
【问题描述】:

我有一个如下的 json 响应

{
    "@odata.context": "some context value here",
    "value": [{
        "@odata.id": "odata id value1",
        "@odata.etag": "W/\"CQEet/1EgOuA\"",
        "Id": "id1",
        "Subject": "subject1"
    }, {
        "@odata.id": "odata id value2",
        "@odata.etag": "W/\"CyEet/1EgOEk1t/\"",
        "Id": "id2",
        "Subject": "subject2"
    }]
}

如何创建一个 bean 类(MyMessage)来使用 spring resttemplate 解析“值”?

RestTemplate rest = new RestTemplate();
ResponseEntity<MyMessage> response = rest.exchange(url, HttpMethod.GET, entity, MyMessage.class);

有人可以帮忙吗?

【问题讨论】:

  • 您确定需要自己处理这个属性吗?我认为你不需要映射它,OData服务器部分会自己找到它并做需要做的事情。
  • 我正在尝试使用 Outlook 邮件 api。他们没有java客户端。 msdn.microsoft.com/office/office365/api/… 。在客户端,我们需要解析此消息以获取邮件详细信息

标签: java json spring resttemplate


【解决方案1】:

使用 @JsonProperty 注释 bean 属性以设置属性的 JSON 字段名称(如果它不同)。

见:

JsonProperty annotationWhen is the @JsonProperty property used and what is it used for?

示例(bean 属性是公开的,例如简单性):

MyMessage 类:

public class MyMessage {

    @JsonProperty("@odata.context")
    public String context;

    @JsonProperty("value")
    public Value[] values;
}

值类:

// PascalCaseStrategy is to resolve Id and Subject properties
@JsonNaming(PascalCaseStrategy.class)
public class Value {

    @JsonProperty("@odata.id")
    public String odataId;

    @JsonProperty("@odata.etag")
    public String odataEtag;

    public String id;
    public String subject;
}

【讨论】:

    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    相关资源
    最近更新 更多