如何使用Jackson为单个键创建多个节点的JSON

huangapple go评论77阅读模式
英文:

How to create JSON for multiple nodes for a single key with jackson

问题

我想使用Java中的Jackson创建一个类似以下的JSON。我可以做到,但只能为单个键。在这种情况下,"TestProject1-staging"不能同时保存"children"和"vars"。

"TestProject1-staging": {
    "children": ["TestProject1-staginga", "TestProject1-stagingb", "TestProject1-stagingc"],
    "vars": {
        "projects": {
            "TestProject1": {
                "app_tier": "apptier",
                "remote_dir": "/release/Test1"
            }
        }
    }
}

这是我编写的代码:

ObjectMapper mapper = new ObjectMapper();
ObjectNode projects = mapper.createObjectNode();
ObjectNode finalObj = mapper.createObjectNode();
ObjectNode proRootNode = mapper.createObjectNode();
ObjectNode children = mapper.createObjectNode();
ObjectNode proRoot = mapper.createObjectNode();
proRoot.put("app_tier", inventoryContainer.appTier);
proRoot.put("remote_dir", inventoryContainer.remoteDirectory);
proRootNode.set(projectRoot, proRoot);
projects.set("projects", proRootNode);
children.put("children", 
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(inventoryContainer.groups));
stagingVarNotSet = false;
finalObj.set(inventoryContainer.projectName, children);
varNode.set("vars", projects);
//finalObj.set(inventoryContainer.projectName, varNode);
System.out.println(StringEscapeUtils.unescapeJava(
     mapper.writerWithDefaultPrettyPrinter().writeValueAsString(finalObj)));

正如你所看到的,被注释的那一行尝试设置vars变量。如果我取消注释它,vars将被打印出来,但children将丢失。在当前的格式中,它打印出了children,但没有vars

那么,我如何同时打印它们两个呢?

如果你想同时打印它们两个,可以将它们合并到一个ObjectNode中,然后将该ObjectNode设置为最终的输出对象。以下是如何修改你的代码:

ObjectMapper mapper = new ObjectMapper();
ObjectNode finalObj = mapper.createObjectNode();
ObjectNode children = mapper.createObjectNode();
ObjectNode proRoot = mapper.createObjectNode();
proRoot.put("app_tier", inventoryContainer.appTier);
proRoot.put("remote_dir", inventoryContainer.remoteDirectory);
children.put("children", 
    mapper.writerWithDefaultPrettyPrinter().writeValueAsString(inventoryContainer.groups));
proRoot.put("projects", proRoot);
finalObj.set(inventoryContainer.projectName, proRoot);
System.out.println(StringEscapeUtils.unescapeJava(
     mapper.writerWithDefaultPrettyPrinter().writeValueAsString(finalObj)));

这样,childrenvars都包含在了同一个proRoot中,并将其设置为最终的输出对象。

英文:

I want to create a JSON like the following using Jackson in Java. I am able to do it but for a single key. In this case "TestProject1-staging" it is not able to save "children" and "vars" simultaneously.

 "TestProject1-staging": {
    "children" : [ "TestProject1-staginga", "TestProject1-stagingb", "TestProject1-stagingc" ],
    "vars": {
        "projects": {
            "TestProject1": {
                "app_tier": "apptier",
                "remote_dir": "/release/Test1"
            }
        }
    }
}

This is the code that I wrote:

ObjectMapper mapper = new ObjectMapper();
ObjectNode projects = mapper.createObjectNode();
ObjectNode finalObj = mapper.createObjectNode();
ObjectNode proRootNode = mapper.createObjectNode();
ObjectNode children = mapper.createObjectNode();
ObjectNode proRoot = mapper.createObjectNode();
proRoot.put("app_tier", inventoryContainer.appTier);
proRoot.put("remote_dir", inventoryContainer.remoteDirectory);
proRootNode.set(projectRoot, proRoot);
projects.set("projects", proRootNode);
children.put("children", 
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(inventoryContainer.groups));
stagingVarNotSet = false;
finalObj.set(inventoryContainer.projectName, children);
varNode.set("vars", projects);
//finalObj.set(inventoryContainer.projectName, varNode);
System.out.println(StringEscapeUtils.unescapeJava(
     mapper.writerWithDefaultPrettyPrinter().writeValueAsString(finalObj)));

As you can see, the commented line tries to set the vars variable. If I uncomment it, vars will be printed but children will be lost. In the current format, it prints the children but not the vars.

So how can I print both of them together?

答案1

得分: 2

包 json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class JSonCreator {
    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.createObjectNode();

        // 创建 TestProject1 JSON 对象
        ObjectNode testProject1Node = mapper.createObjectNode();
        testProject1Node.put("app_tier", "apptier");
        testProject1Node.put("remote_dir", "/release/Test1");

        // 创建 projects JSON 对象
        ObjectNode projectsNode = mapper.createObjectNode();
        projectsNode.set("TestProject1", testProject1Node);

        // 创建 vars JSON 对象
        ObjectNode varsNode = mapper.createObjectNode();
        varsNode.set("projects", projectsNode);

        // 创建 children JSON 数组
        ArrayNode childrenArrayNode = mapper.createArrayNode();
        childrenArrayNode.add("TestProject1-staginga");
        childrenArrayNode.add("TestProject1-stagingb");
        childrenArrayNode.add("TestProject1-stagingc");

        // 创建 children JSON 对象
        ObjectNode childrenNode = mapper.createObjectNode();
        childrenNode.set("children", childrenArrayNode);

        // 创建 TestProject1-staging JSON 对象
        ObjectNode testProject1stagingNode = mapper.createObjectNode();
        testProject1stagingNode.set("children", childrenArrayNode);
        testProject1stagingNode.set("vars", varsNode);

        // 添加到根节点
        ((ObjectNode) rootNode).set("TestProject1-staging",
                testProject1stagingNode);

        // 将 ObjectNode 转换为格式化的 JSON 字符串
        String json = null;
        try {
            json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
                    rootNode);
            // 打印 JSON
            System.out.println(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

输出:

{
  "TestProject1-staging" : {
    "children" : [ "TestProject1-staginga", "TestProject1-stagingb", "TestProject1-stagingc" ],
    "vars" : {
      "projects" : {
        "TestProject1" : {
          "app_tier" : "apptier",
          "remote_dir" : "/release/Test1"
        }
      }
    }
  }
}
英文:

Check if this works for you.

JSonCreator .java

package json;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class JSonCreator {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.createObjectNode();
// Create TestProject1 JSON Object
ObjectNode testProject1Node = mapper.createObjectNode();
testProject1Node.put("app_tier", "apptier");
testProject1Node.put("remote_dir", "/release/Test1");
// Create projects JSON Object
ObjectNode projectsNode = mapper.createObjectNode();
projectsNode.set("TestProject1", testProject1Node);
// Create vars JSON Object
ObjectNode varsNode = mapper.createObjectNode();
varsNode.set("projects", projectsNode);
// Create children JSON Array
ArrayNode childrenArrayNode = mapper.createArrayNode();
childrenArrayNode.add("TestProject1-staginga");
childrenArrayNode.add("TestProject1-stagingb");
childrenArrayNode.add("TestProject1-stagingc");
// Create children JSON object
ObjectNode childrenNode = mapper.createObjectNode();
childrenNode.set("children", childrenArrayNode);
// Create TestProject1-staging" JSON object
ObjectNode testProject1stagingNode = mapper.createObjectNode();
testProject1stagingNode.set("children", childrenArrayNode);
testProject1stagingNode.set("vars", varsNode);
// append into root node
((ObjectNode) rootNode).set("TestProject1-staging",
testProject1stagingNode);
// convert ObjectNode to pretty-print JSON
String json = null;
try {
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
rootNode);
// print json
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}

Output:

{
"TestProject1-staging" : {
"children" : [ "TestProject1-staginga", "TestProject1-stagingb", "TestProject1-stagingc" ],
"vars" : {
"projects" : {
"TestProject1" : {
"app_tier" : "apptier",
"remote_dir" : "/release/Test1"
}
}
}
}
}

huangapple
  • 本文由 发表于 2020年10月1日 04:52:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64145582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定