我正在使用json
数据创建表单。我有一个json
数据,如下所示。
每个主要对象的唯一值都为key
。
从第一个主要对象开始,我需要用其他一些值替换data
对象,它的唯一键是"key": "ticket_type"
。
同样,我必须替换每个对象的某些值。
{
"components": [{
"components": [{
"columns": [{
"pull": 0,
"components": [{
"authenticate": false,
"data": {
"values": [{
"label": "Bug",
"value": 1
}, {
"label": "Feature",
"value": 2
}, {
"label": "Support",
"value": 3
}, {
"label": "Service",
"value": 4
}]
},
"hidden": false,
"defaultValue": "Bug",
"label": "Ticket Type",
"autofocus": false,
"type": "select",
"key": "ticket_type"
}],
"offset": 0,
"width": 4,
"push": 0
}],
"type": "columns",
"hideLabel": true
}, {
"input": false,
"columns": [{
"pull": 0,
"components": [{
"authenticate": false,
"data": {
"values": [{
"label": "Low",
"value": "low"
}, {
"label": "Normal",
"value": "normal"
}, {
"label": "High",
"value": "high"
}, {
"label": "Urgent",
"value": "urgent"
}, {
"label": "Immediate",
"value": "immediate"
}]
},
"hidden": false,
"defaultValue": "normal",
"label": "Priority",
"type": "select",
"labelPosition": "left-right",
"unique": false,
"persistent": true,
"key": "ticket_priority"
}, {
"label": "Parent Task",
"autofocus": false,
"type": "textfield",
"unique": false,
"inputType": "text",
"key": "parent_task"
}],
"offset": 0,
"width": 4,
"push": 0
}, {
"pull": 0,
"components": [{
"hidden": false,
"labelPosition": "left-right",
"defaultValue": "",
"labelMargin": 3,
"customClass": "formio-textfield",
"disabled": true,
"labelWidth": 30,
"block": false,
"label": "Device Name",
"type": "textfield",
"key": 1
}
}],
"offset": 0,
"width": 6,
"push": 2
}],
"tableView": false,
"clearOnHide": false,
"label": "Columns",
"type": "columns",
"key": "panelColumns3",
"hideLabel": true
}, {
"input": true,
"action": "submit",
"theme": "primary",
"label": "Create",
"autofocus": false,
"type": "button",
"disableOnInvalid": false,
"key": "panelCreate"
}],
"title": "New Ticket",
"type": "panel"
}]
}
如何在Java中做到这一点? 目前正在这样做,
JSONArray getArray = jsonData.getJSONArray("components");
JSONObject object1 = getArray.getJSONObject(0);
JSONArray array1 = object1.getJSONArray("components");
array1.getJSONObject(0)
.getJSONArray("columns")
.getJSONObject(0)
.getJSONArray("components")
.getJSONObject(0)
.put("data", jsonTrackerObj);
但是,当我在这些json
数据之间添加任何对象时,以上代码将不起作用。有什么解决办法吗?谢谢。
答案 0 :(得分:0)
您可以使用JsonPath之类的库来轻松访问/修改JSON结构。
这样,您可以使用声明性(因此与排序/嵌套问题无关)的JsonPath表达式轻松访问某些结构,如下所示:
DocumentContext context = JsonPath.parse(json);
// to get all objects that have 'key' = 'ticket_type'
JSONArray array = context.read("$..[?(@.key == 'ticket_type')]");
您还可以像这样修改json结构:
DocumentContext context = JsonPath.parse(json);
JSONObject newValue = new JSONObject().appendField("sample", "field");
// to set 'data' field on all objects that have 'key' = 'ticket_type'
context.set("$..[?(@.key == 'ticket_type')].data", newValue);
PS。您可能需要更改JSON Provider
以适合当前版本-here