简体   繁体   中英

How to create Array of Objects using the Jackson Streaming API

I am trying to create a JSON using the Jackson Streaming API. I know how to create an array of elements in JSON using Jackson as we have plenty of examples related to it. But I am a bit confused about how to create an array of Objects using it.

Following is the JSON structure that I would like to obtain at the end:

{
  "name" : "Batman",
  "year" : 2008,
  "writers":[
    {
      "name" : "Nolan",
      "age"  : 49
    },
    {
      "name" : "Johnathan",
      "age"  : 35
    }
  ]
}

Following is the code I have:

import org.json.JSONObject;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

public class HelloWorld {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        ByteArrayOutputStream jsonStream = new ByteArrayOutputStream();
        JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(jsonStream, JsonEncoding.UTF8);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("name", "Batman");
        jsonGenerator.writeNumberField("year", 2008);
        jsonGenerator.writeFieldName("writers");
        jsonGenerator.writeStartArray();
        // How to to create here objects and add it to the "writers"
        // Should I create another JsonGenerator and create objects usign it?
        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        String jsonData = new String(jsonStream.toByteArray(), "UTF-8");
        JSONObject json = new JSONObject(jsonData);
        System.out.println(json.toString(4));
    }
}

Can someone please guide me on how to create the objects and add them to the array one by one? I am unable to find such an example so posting here.

I would just create a Map to store the data. For the writers , you can call List.of to create an in-line List .

import java.io.*;
import java.util.*;
import com.fasterxml.jackson.databind.*;

public class MovieDataWriter {
    public static void main(String[] args) {
        Map<String, Object> movieData = createMap(
            "name", "Batman",
            "year", 2008,
            "writers", List.of(
                createMap(
                    "name", "Nolan",
                    "age", 49
                ),
                createMap(
                    "name", "Johnathan",
                    "age", 35
                )
            )
        );
        writeToFile(movieData, "target/batman.json");
    }
    
    private static void writeToFile(Map<String, Object> data, String filename) {
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
        try {
            writer.writeValue(new File(filename), data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private static Map<String, Object> createMap(Object ...args) {
        Map<String, Object> pairs = new LinkedHashMap<>();
        for (int i = 0; i < args.length; i += 2) {
            pairs.put(String.valueOf(args[i]), args[i + 1]);
        }
        return pairs;
    }
}

Dependencies

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.1</version>
</dependency>

batman.json

{
  "name" : "Batman",
  "year" : 2008,
  "writers" : [ {
    "name" : "Nolan",
    "age" : 49
  }, {
    "name" : "Johnathan",
    "age" : 35
  } ]
}

After trying a few things I was able to get it. Basically, I had to do the same thing which I was asked in the question. I am not sure why it did not work the first time maybe I missed something. Anyways here is how you can add objects into the array using the Jackson Streaming API . Posting this as it can be beneficial to someone else in the future.

I am creating an array writers in this case and adding the objects into it using the same jsonGenerator .

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.json.JSONObject;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

public class HelloWorld {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        ByteArrayOutputStream jsonStream = new ByteArrayOutputStream();
        JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(jsonStream, JsonEncoding.UTF8);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("name", "Batman");
        jsonGenerator.writeNumberField("year", 2008);
        jsonGenerator.writeFieldName("writers");
        jsonGenerator.writeStartArray();
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("name", "Nolan");
        jsonGenerator.writeNumberField("age", 45);
        jsonGenerator.writeEndObject();
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("name", "Johanathan");
        jsonGenerator.writeNumberField("age", 35);
        jsonGenerator.writeEndObject();
        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        String jsonData = new String(jsonStream.toByteArray(), "UTF-8");
        JSONObject json = new JSONObject(jsonData);
        System.out.println(json.toString(4));
    }
}

You will get the output something like this:

{
    "year": 2008,
    "name": "Batman",
    "writers": [
        {
            "name": "Nolan",
            "age": 45
        },
        {
            "name": "Johanathan",
            "age": 35
        }
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM