[英]how to add attribute at any place in json using JsonObject in java
[英]How to alter any attribute value in the json object using java code
我想使用Java代码替换以下JSON文件中的属性值。
JSON:
{
"featureName": "F1",
"featureVersion": "V1",
"fingerprint":
{
"criteria":
{
"name": "Hostname",
"selector": "0x8",
"item":
{
"rawValue": "myComputer",
"hashValue": "d44fd4dc365481"
}
}
}
}
我想更改featureName属性,选择器属性和hashvalue属性的值。 如何从上面给出的jsonObject更改任何属性的值。
还有其他方法可以做到这一点
使用jq ,您可以使用以下过滤器(即程序):
.featureName = "newfn"
| .fingerprint.criteria.selector = "newcs"
| .fingerprint.criteria.item.hashValue = "newhv"
.featureName = "newfn"
| .fingerprint.criteria
|= (.selector = "newcs" | .item.hashValue = "newhv")
首先通过读取文件来创建JSONObject
。 然后,您可以从现有对象构造一个新的JSONObject
(或者根据您的意愿修改现有JSONObject
),然后将其写回到文件中。
具体实现细节在这里 。
但是,这需要严格的IO操作,并且不适用于大文件,您可能会遇到OOM错误。
使用JSONObject(org.json)
码
JSONObject jsonObject = new JSONObject(urJsonStr);
JSONObject fingerprintObj = jsonObject.getJSONObject("fingerprint");
JSONObject itemObj = fingerprintObj.getJSONObject("item");
itemObj.put("hashValue", "new value");
fingerprintObj.put("item", itemObj);
fingerprintObj.put("selector", "new value");
jsonObject.put("fingerprint", fingerprintObj);
jsonObject.put("featureName", "new value");
请尝试此代码。
JSON:
String jsonString = {
"featureName": "F1",
"featureVersion": "V1",
"fingerprint":
{
"criteria":
{
"name": "Hostname",
"selector": "0x8",
"item":
{
"rawValue": "myComputer",
"hashValue": "d44fd4dc365481"
}
}
}
}
JSONObject jsonResult = new JSONObject(jsonString);
String jsonResult1 = (String)jsonResult.getString("jsonResult");
String jsonResult1 = jsonResult1.replace("F1","your data");
JSONObject fingerprintObj = (JSONObject)jsonResult.getJSONObject("fingerprint");
JSONObject criteria = (JSONObject)fingerprintObj.getJSONObject("criteria");
String hashValue =(String)criteria.getStirng("hashValue");
String hashValue = hashValue.replace("d44fd4dc365481","newdata");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.