有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java通过rest服务在JSON中动态添加property:value

我们如何通过REST服务将json属性作为用户的输入动态创建json属性:值,而不需要字段来保存值

基本上,目前的产出是:

{
    "name": "X",
    "price": "X",
    "ticker": "X",
    "status": "X",
    "supplier": "X",
    "attribute": [{
            "key": "index",
            "value": "Nasdaq"
        },
        {
            "key": "priority",
            "value": "high"
        }
    ]
}

所需输出为:

{
    "name": "X",
    "price": "X",
    "ticker": "X",
    "status": "X",
    "supplier": "X",
    "attribute": [{
            "index": "Nasdaq"
        },
        {
            "priority": "high"
        }
    ]
}

这里,index和Nasdaq是用户给定的值,这是要添加到属性列表中的键值对

使用的两个POJO:

股票。爪哇

@XmlRootElement
public class Stock {

    public Stock() {

    }

    public Stock(String name, double price, String ticker, String status, String supplier, List<KV> attribute) {
        super();
        this.name = name;
        this.price = price;
        this.ticker = ticker;
        this.status = status;
        this.supplier = supplier;
        this.attribute = attribute;
    }

    private String name;
    private double price;
    private String ticker;
    private String status;
    private String supplier;

    private List<KV> attribute;


    public List<KV> getAttribute() {
        return attribute;
    }


    public void setAttribute(List<KV> attribute) {
        this.attribute = attribute;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

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

    public String getTicker() {
        return ticker;
    }

    public void setTicker(String ticker) {
        this.ticker = ticker;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getSupplier() {
        return supplier;
    }

    public void setSupplier(String supplier) {
        this.supplier = supplier;
    }

}

以及: 千伏。爪哇

public class KV {
    private String key;
    private String value;

    public KV(String key, String value) {
        super();
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

我更喜欢与注释的使用或rest服务中的更改有关的答案,而不是最后的文本处理


共 (2) 个答案

  1. # 1 楼答案

    好的,一旦得到当前的响应,就可以创建一个Hashmap,而不是一个类“public class KV{}”, &;Hashmap的键可以保存索引/优先级等;价值可以保持在纳斯达克/高位

    还可以将Hashmap变量命名为“attribute”

    这样,您就可以使用当前的结构从API中提取数据;然后可以像我上面说的那样把它转换成一个&;发送回复