我有这样的杰森:
{
"attachments": [
"string"
],
"contact": {
"name": "Mahesh"
},
"contactCode": "C-0000001",
"journalEntryCode": "JE-0000002",
"linkedDocuments": [
{
"contactCode": "C-0000001",
"documentCode": "0000018",
"documentItemDetails": [
{
"productCode": "P-0000001"
}
],
"documentType": "QUOTATION",
}
],
"taxAmount": 2.322,
"totalAmount": 12.322,
"unitPriceGstInclusive": false
}
我想在“ linkedDocuments”下放置/替换“ documentCode”的新值“ 1234”
我尝试通过采用json路径进行跟踪:
JSONObject requestParams = Utilities.readJSON("createInvoiceFromQuote.json");
requestParams.put("$.linkedDocuments[*].documentCode", "1234");
但这只是在json的末尾创建一个新字段“ $ .linkedDocuments [*]。documentCode”
{
"attachments": [
"string"
],
"contact": {
"name": "Mahesh"
},
"contactCode": "C-0000001",
"journalEntryCode": "JE-0000002",
"linkedDocuments": [
{
"contactCode": "C-0000001",
"documentCode": "0000018",
"documentItemDetails": [
{
"productCode": "P-0000001"
}
],
"documentType": "QUOTATION",
}
],
"taxAmount": 2.322,
"totalAmount": 12.322,
"unitPriceGstInclusive": false
"$.linkedDocuments[*].documentCode":"1234"
}
应该是这样
{
"attachments": [
"string"
],
"contact": {
"name": "Mahesh"
},
"contactCode": "C-0000001",
"journalEntryCode": "JE-0000002",
"linkedDocuments": [
{
"contactCode": "C-0000001",
"documentCode": "1234",
"documentItemDetails": [
{
"productCode": "P-0000001"
}
],
"documentType": "QUOTATION",
}
],
"taxAmount": 2.322,
"totalAmount": 12.322,
"unitPriceGstInclusive": false
}
如何使用Java放置/替换嵌套字段值?
最佳答案
由于linkedDocuments是JSONObject的JSONArray,因此“ $ .linkedDocuments [*]。documentCode”键将无法正常工作。要更新JSONArray中JSONObject的任何键,请访问JOSNArray并迭代所有JSONObject,然后执行更新。
String str = "{\"attachments\":[\"string\"],\"contact\":{\"name\":\"Mahesh\"},\"contactCode\":\"C-0000001\",\"journalEntryCode\":\"JE-0000002\",\"linkedDocuments\":[{\"contactCode\":\"C-0000001\",\"documentCode\":\"0000018\",\"documentItemDetails\":[{\"productCode\":\"P-0000001\"}],\"documentType\":\"QUOTATION\"},{\"contactCode\":\"C-0000002\",\"documentCode\":\"0000019\",\"documentItemDetails\":[{\"productCode\":\"P-0000002\"}],\"documentType\":\"QUOTATION\"}],\"taxAmount\":2.322,\"totalAmount\":12.322,\"unitPriceGstInclusive\":false}";
JSONObject jsonObject = new JSONObject(str);
JSONArray array = jsonObject.getJSONArray("linkedDocuments");
array.getJSONObject(0).put("documentCode", 1234);
System.out.println(jsonObject);
输出:
{
"linkedDocuments": [
{
"documentCode": 1234,
"contactCode": "C-0000001",
"documentType": "QUOTATION",
"documentItemDetails": [
{
"productCode": "P-0000001"
}
]
},
{
"documentCode": "0000019",
"contactCode": "C-0000002",
"documentType": "QUOTATION",
"documentItemDetails": [
{
"productCode": "P-0000002"
}
]
}
],
"totalAmount": 12.322,
"attachments": [
"string"
],
"contactCode": "C-0000001",
"contact": {
"name": "Mahesh"
},
"journalEntryCode": "JE-0000002",
"taxAmount": 2.322,
"unitPriceGstInclusive": false
}