我们如何通过 REST 服务将其作为用户的输入来动态创建 json property:value,而无需使用字段来保存值。
基本上,当前的输出是:
{
"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:
Stock.java
@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;
}
}
并且: KV.java
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;
}
}
更喜欢与注释的使用或其余服务中的更改相关的答案,而不是最后的文本处理。
最佳答案
好的,一旦你得到了当前得到的响应,那么你可以创建一个 Hashmap,而不是类“public class KV {}”, &Hashmap的key可以保存索引/优先级等&value可以保存Nasdaq/high。
还将 Hashmap 变量命名为“属性”。
这样您就可以使用当前的结构从 API 中提取数据,然后将其转换为我上面所说的数据并发送响应。
关于java - 动态添加属性:value in JSON through rest services,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47130699/