如何使用java代码更改json对象中的任何属性值

如何使用java代码更改json对象中的任何属性值,java,json,jq,Java,Json,Jq,我想用java代码替换下面JSON文件中的属性值 JSON: 我想更改featureName属性、selector属性和hashvalue属性的值。如何更改上述jsonObject中任何属性的值 还有别的办法吗 使用,您可以使用如下过滤器(即程序): .featureName = "newfn" | .fingerprint.criteria.selector = "newcs" | .fingerprint.criteria.item.hashValue = "newhv" 烘干机 通过读取

我想用java代码替换下面JSON文件中的属性值

JSON:

我想更改featureName属性、selector属性和hashvalue属性的值。如何更改上述jsonObject中任何属性的值

还有别的办法吗

使用,您可以使用如下过滤器(即程序):

.featureName = "newfn"
| .fingerprint.criteria.selector = "newcs"
| .fingerprint.criteria.item.hashValue = "newhv"
烘干机
通过读取文件,首先创建一个
JSONObject
。然后,您可以从现有对象构建一个新的
JSONObject
(或者根据您的意愿修改现有对象),并将其写回文件

具体实施细节如下所示

但是,这需要严重的IO操作,并且不适用于大型文件,您可能会遇到OOM错误。

使用JSONObject(org.json)

代码

请尝试此代码

JSON:


对这两个问题我都同意。
.featureName = "newfn"
| .fingerprint.criteria.selector = "newcs"
| .fingerprint.criteria.item.hashValue = "newhv"
.featureName = "newfn"
| .fingerprint.criteria
  |= (.selector = "newcs" | .item.hashValue = "newhv")
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");
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");