Creating a json object using jackson

前端 未结 4 1973
孤城傲影
孤城傲影 2020-12-05 13:26

How can I create a json array like the example below using jackson.

I tried using ObjectMapper, but this does not seem correct.

      try (Director         


        
相关标签:
4条回答
  • 2020-12-05 13:32

    You need a JsonNodeFactory:

    final JsonNodeFactory factory = JsonNodeFactory.instance;
    

    This class has methods to create ArrayNodes, ObjectNodes, IntNodes, DecimalNodes, TextNodes and whatnot. ArrayNodes and ObjectNodes have convenience mutation methods for adding directly most JSON primitive (non container) values without having to go through the factory (well, internally, they reference this factory, that is why).

    As to an ObjectMapper, note that it is both a serializer (ObjectWriter) and deserializer (ObjectReader).

    0 讨论(0)
  • 2020-12-05 13:38

    initializing JSON object as singleton instance, and building it:

    ObjectNode node = JsonNodeFactory.instance.objectNode(); // initializing
    node.put("x", x); // building
    

    PS: to println use node.toString().

    0 讨论(0)
  • 2020-12-05 13:44

    You can write an object to a json string. So I hope you have your data in an object of a class defined as per your need. Here is how you can convert that object into a json string:

    //1. Convert Java object to JSON format
    ObjectMapper mapper = new ObjectMapper();
    
    String jsonString = mapper.writeValueAsString(yourObject);
    

    See here for the full jackson-databind javadoc.

    0 讨论(0)
  • 2020-12-05 13:50

    You can do this without creating POJO and converting it into JSON. I assume your data in the Record object.

            JsonNode rootNode = mapper.createObjectNode();
            ArrayNode childNodes = mapper.createArrayNode();
            for (Record record : records) {
                JsonNode element = mapper.createObjectNode();
                ((ObjectNode) element).put("mime": record.getDirectory());
                      //fill rest of fields which are needed similar to this.
                      //Also here record.getDirectory() method will should return "directory"
                      //according to your json file.
                childNodes.add(element);
            }
            ((ObjectNode) rootNode).put("files", childNodes);
    
    0 讨论(0)
提交回复
热议问题