Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用任何现有java库/工具对输入样本进行JSON到JSON转换_Java_Json_Jackson_Jolt_Json Patch - Fatal编程技术网

使用任何现有java库/工具对输入样本进行JSON到JSON转换

使用任何现有java库/工具对输入样本进行JSON到JSON转换,java,json,jackson,jolt,json-patch,Java,Json,Jackson,Jolt,Json Patch,输入: 要求的输出: { "Student": { "name" :"abc", "id" : 588, "class : "12" } } 您的输出json无效。Json对象不能复制密钥 您可以使用库org.json执行以下操作: { "Student": { "key" :"name", "value":"abc", "key" :"id", "value":"588",

输入:

要求的输出:

 {
   "Student": {
      "name" :"abc",
      "id"   : 588, 
      "class : "12"
   }
 } 

您的输出json无效。Json对象不能复制密钥

您可以使用库
org.json
执行以下操作:

 {
   "Student": {

      "key" :"name",
      "value":"abc",

      "key" :"id",
      "value":"588",

      "key" :"class",
      "value":"12"
   }
 } 
输出:

    JSONObject jsonObject = new JSONObject(inputJson);
    JSONObject outputJson = new JSONObject();
    JSONArray array = new JSONArray();

    for (Object key : jsonObject.keySet()) {
       JSONObject item = new JSONObject();

       String keyStr = (String)key;
       Object keyvalue = jsonObj.get(keyStr);
       item.put(keyStr, keyvalue);
       array.put(item);

    }
    outputJson.put("Student", array);
    System.out.println(json.toString());

与另一个答案类似,所需的输出JSON格式无效

最接近的有效输出是

 {
    "Student": [

        {
            "key": "name",
            "value": "abc"
        },

        {
            "key": "id",
            "value": "588"
        },
        {
            "key": "class",
            "value": "12"
        }
    ]

 }
这可以通过具有以下规范的Jolt生成

{
  "Student" : [ {
    "key" : "name",
    "value" : "abc"
  }, {
    "key" : "id",
    "value" : 588
  }, {
    "key" : "class",
    "value" : "12"
  } ]
}

如果我们假设输出是有效的JSON,则很容易解决这个问题,方法是像其他响应者一样生成一个键/值对象数组

array
函数将一个对象转换为与您要求的完全相同的键/值对象数组,因此转换为:

[
  {
    "operation": "shift",
    "spec": {
      "Student": {
        "name": {
          "$": "Student[0].key",
          "@": "Student[0].value"
        },
        "id": {
          "$": "Student[1].key",
          "@": "Student[1].value"
        },
        "class": {
          "$": "Student[2].key",
          "@": "Student[2].value"
        }
      }
    }
  }
]

请核对我的答案。
{"Student" : array(.Student)}