简体   繁体   English

从 JSON 数组创建 POJO(BufferReader)

[英]POJO Creation from JSON Array (BufferReader)

I am trying to unmarshal the following JSON我正在尝试解组以下 JSON

[{
    "myId": "12851cb3087f51b4fb392b1fea36eef9508",
    "secondaryId": "787CFD4A-6B1D-4415-AD56-D075B535B890",
    "my_key": "keyABCD",
    "email": ""
}, {
    "myId": "12851cb3087f51b4fb392b1fea36eef9508",
    "secondaryId": "BFACD2F0-F5EF-4F05-AA6B-00E18CA907EF",
    "my_key": "keyABCD",
    "email": ""
}, {
    "myId": "12851cb3087f51b4fb392b1fea36eef9508",
    "secondaryId": "567DE8C0-B5B5-4961-B97A-A2DD374AEED1",
    "my_key": "keyABCD",
    "email": ""
}, {
    "myId": "12851cb3087f51b4fb392b1fea36eef9508",
    "secondaryId": "78a52d90-be6c-4d80-b79d-0e256028ba01",
    "my_key": "keyABCD",
    "email": "test@email.com"
}, {
    "myId": "12851cb3087f51b4fb392b1fea36eef9508",
    "secondaryId": "aeb148e7-fc88-4a71-8baa-63b6528e463e",
    "my_key": "keyABCD",
    "email": ""
}]

and already have a bufferreader ( myBufferedReader ) which has the above json. POJO并且已经有一个 bufferreader ( myBufferedReader ) 上面有 json. POJO

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@ToString
@AllArgsConstructor
public class MyPOJO {
    @Getter @Setter private String myId;
    @Getter @Setter private String secondaryId;
    @Getter @Setter private String my_key;
    @Getter @Setter private String email;

}

On using below mapper -在使用下面的映射器时 -

ObjectMapper mapper = new ObjectMapper();
List<MyPOJO> eventList = mapper.readValue(myBufferedReader.readLine(),mapper.getTypeFactory().constructCollectionType(List.class, MyPOJO.class));

getting error.得到错误。 Please help.请帮忙。 - (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator) -(没有创建者,如默认构造,存在):无法从 Object 值反序列化(没有基于委托或属性的创建者)

If above is not the correct way, please suggest the best way to read from bufferreader and create list of pojo class mapped with json.如果以上不是正确的方法,请建议从 bufferreader 读取并创建映射到 json 的 pojo class 列表的最佳方法。

Regards, Dan问候, 丹

Well, I am not a Master of all things Java JSON .好吧,我不是Java JSON I have a tool which I use whenever I need to parse JSON .我有一个工具,每当我需要解析JSON时都会使用它。 Be aware that there are multiple tools for parsing JSON String's , but I am only going to post the solution for the version that I use.请注意,有多种工具可以解析JSON String's ,但我只会发布我使用的版本的解决方案。 I, personally, do not get into Java's Component Annotations because they add such a tremendous amount of complexity, and do not add anything to value of the code.我个人不会使用 Java 的组件Annotations ,因为它们增加了如此巨大的复杂性,并且不会增加代码的任何价值。 I am not here to prove my points, but I don't get into Java Beans .我不是来证明我的观点的,但我不进入Java Beans

There is a library called the GSON Library that (supposedly) can map JSON String's directly to Java Object's ( POJO's as you called them).有一个名为GSON的库(据说)可以将 map JSON String's直接转换为 Java Object's (您称之为POJO )。 I am, unfortunately, unfamiliar with the GSON Tool, and it might actually be able to "automatically" build a class MyPOJO using Annotations as you have requested.不幸的是,我不熟悉GSON工具,它实际上可以按照您的要求使用Annotations “自动”构建class MyPOJO

Here is my solution, which just uses the standard JSON Parsing Library which I call javax.json.* below.这是我的解决方案,它只使用标准的JSON 解析库,我在下面称之为javax.json.* You would have to retrieve the JSON JAR by looking for it using a Google Search .您必须使用Google 搜索来检索JSON JAR

import java.io.*;
import javax.json.*;

public class S
{
    // I am just going to create the class for parsing this
    // If there is a GSON way to do this "Automatically", then you
    // should not use this Answer I have written to Stack Overflow

    public static class MyPOJO
    {
        public final String myId;
        public final String secondaryId;
        public final String myKey;
        public final String email;

        public MyPOJO(String myId, String secondaryId, String myKey, String email)
        { this.myId=myId; this.secondaryId=secondaryId; this.myKey=myKey; this.email=email; }

        public String toString()
        {
            return
                "myId:         " + myId         + '\n' +
                "seoondaryId:  " + secondaryId  + '\n' +
                "myKey:        " + myKey        + '\n' +
                "email:        " + email        + "\n\n";
        }
    }

    public static void main(String[] argv) throws IOException
    {
        // This reads the 'input.json' file into the Json parser using
        // a simple java.io.FileReader
        Reader r = new FileReader("input.json");

        // This reads the file, and retrieves the JsonArray that you
        // have provided in your original post.
        JsonArray ja = Json
            .createReader(r)
            .readArray();
        
        for (JsonObject jo : ja.getValuesAs(JsonObject.class))
        {
            String myId         = jo.getString("myId");
            String secondaryId  = jo.getString("secondaryId");
            String myKey        = jo.getString("my_key");
            String email        = jo.getString("email");

            // What *I* would do is to get rid of the Component Annotation, and simply 
            // use a Constructor.  I don't strongly believe in Java's Annotation Classes,
            // and I never use them.  If you can find an AUTOMATED WAY to do all of this,
            // YOU SHOULD ... - if you are willing to learn it all.
            // I HAVE NOT! :)
            
            // If there is an easy way to **DIRECTLY MAP** a JSON Object to a specified
            // class - and I believe that the GSON library is capable of directly mapping
            // JSON Object's to GSON Java POJO's (Java Object's), but I have not used them
            // before.  My own personal belief is that if it were easier, then learning the
            // GSON JAR Library and Java Documentation (JavaDoc) for GSON.

            // Here, though, a Constructor is what I would prefer myself.
            MyPOJO mp = new MyPOJO(myId, secondaryId, myKey, email);
            System.out.println(mp.toString());
        }
    }
}

The following is output by the above class to the Shell Terminal:下面是output由上面的class到Shell终端:

@cloudshell:~$ java S
myId:         12851cb3087f51b4fb392b1fea36eef9508
seoondaryId:  787CFD4A-6B1D-4415-AD56-D075B535B890
myKey:        keyABCD
email:        


myId:         12851cb3087f51b4fb392b1fea36eef9508
seoondaryId:  BFACD2F0-F5EF-4F05-AA6B-00E18CA907EF
myKey:        keyABCD
email:        


myId:         12851cb3087f51b4fb392b1fea36eef9508
seoondaryId:  567DE8C0-B5B5-4961-B97A-A2DD374AEED1
myKey:        keyABCD
email:        


myId:         12851cb3087f51b4fb392b1fea36eef9508
seoondaryId:  78a52d90-be6c-4d80-b79d-0e256028ba01
myKey:        keyABCD
email:        test@email.com


myId:         12851cb3087f51b4fb392b1fea36eef9508
seoondaryId:  aeb148e7-fc88-4a71-8baa-63b6528e463e
myKey:        keyABCD
email:        

Add your default constructor, empty constructor, by adding @NoArgConstructor top of your POJO class. Then simply convert your buffer reader JSON string to a list of POJO like this:通过在 POJO class 顶部添加@NoArgConstructor添加默认构造函数,空构造函数。然后只需将缓冲区读取器 JSON 字符串转换为 POJO 列表,如下所示:

List<MyPOJO> eventList = mapper.readValue(myBufferedReader, new TypeReference<List<MyPOJO>>(){});

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

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