我有一个像这样的 json 字符串
{
"code": "200",
"data": "",
"datadetail": null,
"message": "Khách hàng không tồn tại",
"description": "KH_NOTFOUND:"
}
因为 data 属性的值为“”,所以对象映射器无法将该字段映射到 Java POJO,无论如何都要将 data 属性的值修改为特定字符串,如下所示
{
"code": "200",
"data": "no data",
"datadetail": null,
"message": "Khách hàng không tồn tại",
"description": "KH_NOTFOUND:"
}
详情
Can not instantiate value of type [collection type; class java.util.ArrayList, contains [simple type, class vnptpay.collection.adapter.partner.water.laichau.Datum]] from String value (''); no single-String constructor/factory method
这是我要映射的目标java对象类
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"code",
"data",
"datadetail",
"message",
"description"
})
@JsonIgnoreProperties(ignoreUnknown = true)
public class GetBillResponse implements Serializable{
@JsonProperty("code")
private String code;
@JsonProperty("data")
private ArrayList<Datum> data = null;
@JsonProperty("datadetail")
private Object datadetail;
@JsonProperty("message")
private String message;
@JsonProperty("description")
private String description;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
这是我的映射代码
ObjectMapper mapper = new ObjectMapper();
GetBillResponse obj = null;
obj = mapper.readValue(output.toString(), GetBillResponse.class);
最佳答案
假设output.toString()是你的JSON字符串,你可以添加.replace("\"\"",\"{none}\")。 Java应该能够将其解释为具有一个元素的ArrayList(也许我的语法是错误的,但肯定有一种方法可以从字符串初始化ArraList)。
编辑:现在我想了一下,您可能需要 JSON 语法,而不是 Java 语法,因此 .replace("\"\"",\"[]\") 或类似的东西。
关于java - 修改json字符串中的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57568144/