通过路径将数组添加到json的键

时间:2015-12-17 08:49:44

标签: java json

我有以下JSON结构

'%s:17:"-Entrepreneurship";%'

我需要将值[“1”,“2”]的新键“myName”添加到某个节点。例如,结果json将是:

[
  {
    "key": "val",
    "type": "myType",
    "someSubJson": {
      "key": "val"
    }
  },
  {
    "key": "val",
    "type": "myType"
  }
]

我已经尝试过com.jayway.jsonpath但是当我的值是数组时它不起作用。也许是另一种方式来做或我错过了什么?

由于

PS

这里有一些我试图运行的示例代码

[
  {
    "key": "val",
    "type": "myType",
    "someSubJson": {
      "key": "val"
    },
    "myName": ["1", "2"]
  },
  {
    "key": "val",
    "type": "myType"
  }
]

在myName键中,我接受了获取我的数组但得到“myName”:{}

2 个答案:

答案 0 :(得分:0)

这是很晚的回复,但可能会对某人有所帮助:)做到这一点的一种方法如下:

import org.json.JSONArray;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;

public class Test {

    public static void main(String[] args) {
        // JSON provided as input
        String rawJson = "[{\"key\":\"val\",\"type\":\"myType\",\"someSubJson\":{\"key\":\"val\"}},{\"key\":\"val\",\"type\":\"myType\"}]";

        // xpath for adding into first element of JSON array
        String xpath = "$.[0].myName";

        Test test = new Test();

        System.out.println(test.insertValue(rawJson, xpath));

    }

    private String insertValue(String rawJson, String xpath) {

        // Configuration ensuring addition of new leaves without raising exception
        Configuration conf = Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL).addOptions(Option.SUPPRESS_EXCEPTIONS);  
        DocumentContext documentContext = JsonPath.using(conf).parse(rawJson);

        documentContext.set(JsonPath.compile(xpath), new JSONArray(new int[]{1,2}));

        return documentContext.jsonString();
    }

}

输出:

[
  {
    "key": "val",
    "type": "myType",
    "someSubJson": {
      "key": "val"
    },
    "myName": [
      1,
      2
    ]
  },
  {
    "key": "val",
    "type": "myType"
  }
]

答案 1 :(得分:-1)

我建议使用Jackson而不是JayWay。杰克逊有很多选择与Jayson JSON对象一起玩。