RESTFul WebService-如何将类变量表示为其他json名称

时间:2018-10-25 15:52:28

标签: java json rest jax-rs

我才刚刚开始学习Restful网络服务,并从事一项需要在调用特定GET方法时返回Product类对象详细信息的任务。

我想发送回-{“ product_id”:123,“ price”:35.50,“ currency”:“ SGD”,“ total_items”:1000,“ items_left”:450,“ time_left”:100000}

但是我得到的响应为(请注意重复)-{“ availableQuantity”:45,“ currency”:“ SGD”,“ items_left”:45,“ price”:35.5,“ product_id”:1, “ productId”:1,“ time_left”:10000,“ timeAvailable”:10000,“ total_items”:100,“ totalItems”:100}

我的产品类别为-

public class Product {
    @XmlAttribute(name = "product_id")
    private int productId;
    private double price;
    private String currency;
    @XmlAttribute(name = "total_items")
    private int totalItems;

    public int getTotalItems() {
        return totalItems;
    }

    public void setTotalItems(int totalItems) {
        this.totalItems = totalItems;
    }

    @XmlAttribute(name = "items_left")
    private int availableQuantity;
    @XmlAttribute(name = "time_left")
    private long timeAvailable;

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public int getAvailableQuantity() {
        return availableQuantity;
    }

    public void setAvailableQuantity(int availableQuantity) {
        this.availableQuantity = availableQuantity;
    }

    public long getTimeAvailable() {
        return timeAvailable;
    }

    public void setTimeAvailable(long timeAvailable) {
        this.timeAvailable = timeAvailable;
    }

    public Product(int id, double price, String currency, int totalItems, int itemsLeft, long timeLeft) {
        this.productId = id;
        this.price = price;
        this.currency = currency;
        this.totalItems = totalItems;
        this.availableQuantity = itemsLeft;
        this.timeAvailable = timeLeft;
    }
}

如何删除重复项并返回期望值(即使我的类变量使用不同的名称)?对于任何不正确/丢失的信息表示歉意!

2 个答案:

答案 0 :(得分:1)

似乎您还有另一个依赖项会自动序列化您的对象。

如果它是Boost.Date_Time(Spring Boot中的默认映射依赖项),则可以将@XmlAttribute(name = "product_id")替换为@JsonProperty("product_id")

答案 1 :(得分:0)

You may use below jackson annotations.

For the order of elements in response use @JsonPropertyOrder的宽度并更改响应中的名称,只需使用@JsonProperty(value =“ NEW_NAME”)批注

在您的示例中,就像

@JsonPropertyOrder({"productId","price","currency","totalItems"})
public class Product {

     @JsonProperty(value="product-id")
     private int productId;

     private double price;

     @JsonProperty(value="total_items")
     private int totalItems;

     private String currency;

      ................
      ...............

See this link for more information on Jackson Annotations