简体   繁体   English

如何使用 Jackson 流创建对象数组 API

[英]How to create Array of Objects using the Jackson Streaming API

I am trying to create a JSON using the Jackson Streaming API.我正在尝试使用 Jackson 流式传输 API 创建 JSON。 I know how to create an array of elements in JSON using Jackson as we have plenty of examples related to it.我知道如何使用 Jackson 在 JSON 中创建元素数组,因为我们有很多与之相关的示例。 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:以下是我想在最后获得的 JSON 结构:

{
  "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.我只想创建一个Map来存储数据。 For the writers , you can call List.of to create an in-line List .对于writers ,您可以调用List.of来创建一个内联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蝙蝠侠.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 .无论如何,这里是如何使用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 .在这种情况下,我正在创建一个数组writers器,并使用相同的jsonGeneratorobjects添加到其中。

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:你会得到 output 是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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