简体   繁体   English

在REST API响应中更改字段名称

[英]Changing field names in REST API response

Hi I'm a newbie so I may not understand high level solutions ! 嗨,我是新手,所以我可能不懂高级解决方案!

So coming to the point I want to send a response for a REST API. 所以我想发送REST API的响应。 So what basically happening is that I'm returning an object from a method and then the fields of those objects along with their corresponding values get displayed in the API response. 所以基本上发生的是我从方法中返回一个对象,然后这些对象的字段及其对应的值将显示在API响应中。

To be clear lets say we have a class defined as 要清楚,我们假设我们有一个定义为的类

Class Sample
{
    String fruit;
    int cost;
}

Now lets say we have an object of the above class (Sample abc). 现在假设我们有一个上述类的对象(Sample abc)。 Also we have a method as below: 我们还有一个方法如下:

@RequestMapping(/inventory)
public Sample getInventory()
{
    Sample abc = new Sample();
    ----Some processing----
    return abc;
}

So the response I'm getting is that 所以我得到的回应是

{
    "fruit":"apple",
    "cost":100
}

Now what I want is "fruit.name" in the response, but obviously I can't have a field with that name(having dot or @ characters) ! 现在我想要的是响应中的“fruit.name”,但显然我不能有一个具有该名称的字段(有点或@字符)!

{
    "fruit.name":"apple",
    "cost@Dollars":100
}

So is there any way with the help of which I can get this kind of response ? 那么有什么方法可以帮助我获得这种反应?

If you're using Jackson you could use @JsonProperty 如果你正在使用杰克逊,你可以使用@JsonProperty

public class Sample {
  @JsonProperty("fruit.name")
  public String fruit;
  @JsonProperty("cost@Dollars")
  public int cost; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM