POJO从JSON数组(BufferReader)创建

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

POJO Creation from JSON Array (BufferReader)

问题

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

// ... (import statements and other code)

// Your existing code for the MyPOJO class

public class Main {
    public static void main(String[] args) {
        // Assuming you have your BufferedReader named myBufferedReader

        ObjectMapper mapper = new ObjectMapper();
        try {
            String jsonLine;
            StringBuilder jsonContent = new StringBuilder();
            
            while ((jsonLine = myBufferedReader.readLine()) != null) {
                jsonContent.append(jsonLine);
            }

            String json = jsonContent.toString();
            List<MyPOJO> eventList = mapper.readValue(json, new TypeReference<List<MyPOJO>>() {});

            // Now you have your list of MyPOJO objects
            for (MyPOJO pojo : eventList) {
                System.out.println(pojo.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Please note that I've provided the code translation for the Java code you provided. If you have any issues or further questions, feel free to ask.

英文:

I am trying to unmarshal the following JSON

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

and already have a bufferreader (myBufferedReader) which has the above 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&lt;MyPOJO&gt; 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)

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.

Regards,
Dan

答案1

得分: 1

Well, I am not a Master of all things **`Java JSON`**.  I have a tool which I use whenever I need to parse **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.  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.  I am not here to prove my points, but I don't get into **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).  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.

Here is my solution, which just uses the standard **JSON Parsing Library** which I call [`javax.json.*`](https://docs.oracle.com/javaee/7/api/javax/json/package-summary.html) below.  You would have to retrieve the **JSON JAR** by looking for it using a **Google Search**.

```java
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:

@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:        
英文:

Well, I am not a Master of all things Java JSON. I have a tool which I use whenever I need to parse JSON. Be aware that there are multiple tools for parsing JSON String&#39;s, but I am only going to post the solution for the version that I use. 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. I am not here to prove my points, but I don't get into Java Beans.

There is a library called the GSON Library that (supposedly) can map JSON String&#39;s directly to Java Object&#39;s (POJO's as you called them). 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.

Here is my solution, which just uses the standard JSON Parsing Library which I call javax.json.* below. You would have to retrieve the JSON JAR by looking for it using a Google Search.

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 &quot;Automatically&quot;, 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
&quot;myId:         &quot; + myId         + &#39;\n&#39; +
&quot;seoondaryId:  &quot; + secondaryId  + &#39;\n&#39; +
&quot;myKey:        &quot; + myKey        + &#39;\n&#39; +
&quot;email:        &quot; + email        + &quot;\n\n&quot;;
}
}
public static void main(String[] argv) throws IOException
{
// This reads the &#39;input.json&#39; file into the Json parser using
// a simple java.io.FileReader
Reader r = new FileReader(&quot;input.json&quot;);
// 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(&quot;myId&quot;);
String secondaryId  = jo.getString(&quot;secondaryId&quot;);
String myKey        = jo.getString(&quot;my_key&quot;);
String email        = jo.getString(&quot;email&quot;);
// What *I* would do is to get rid of the Component Annotation, and simply 
// use a Constructor.  I don&#39;t strongly believe in Java&#39;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&#39;s to GSON Java POJO&#39;s (Java Object&#39;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:

@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:        

答案2

得分: 1

Add your default constructor, empty constructor, by adding @NoArgConstructor on top of your POJO class.
Then simply convert your buffer reader JSON string to a list of POJO like this:

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

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:

List&lt;MyPOJO&gt; eventList = mapper.readValue(myBufferedReader, new TypeReference&lt;List&lt;MyPOJO&gt;&gt;(){});

huangapple
  • 本文由 发表于 2020年10月8日 05:13:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64252380.html
匿名

发表评论

匿名网友

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

确定