简体   繁体   中英

Getting a Mongodb ArrayOfObjects value from POJO class with Java driver

I am facing an issue(getting Null Value) while getting the Mongodb value from the ArrayOfObjects and My POJO class is like below:I have created separate POJOS for Each Object.Can anyone help me how to fetch the value of Email Systems.Bob.System. My Document:

"Email Systems" : [
        {
            "Bob" : {
                "System" : "Bob", 
                "result" : true
            }
        }, 
        {
            "Wild" : {
                "System" : "Wild", 
                "result" : true
            }
        },
        {
            "CRaft" : {
                "System" : "Craft", 
                "result" : false
            }
        }
    ]

My POJO Class:

public class Bob{
    @JsonProperty("System") 
    public String system;
    public String result;
}

public class Wild{
    @JsonProperty("System") 
    public String system;
    public String result;
}

public class CRaft{
    @JsonProperty("System") 
    public String system;
    public String result;
}

public class EmailSystem{
    @JsonProperty("Bob") 
    public Bob bob;
    @JsonProperty("Wild") 
    public Wild wild;
    @JsonProperty("CRaft") 
    public CRaft cRaft;
}

public class Root{
    @JsonProperty("EmailSystems") 
    public List<EmailSystem> emailSystems;
}

1st populate the JSON data to your POJO the try to retrieve from them then you will not get null value.

Make sure you have GETTER/SETTER in all POJO. and also "result" field is boolean . but you can map with string with("")

ObjectMapper obj = new ObjectMapper();

Root root = obj.readValue("jsonstring",Root.class);

they you can use getter to get the data.

POM dependency:--

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

your JSON should be now:--- (as per POJO class)

  {
  "root": {
    "EmailSystems": [
      {
        "Bob": {
          "System": "Bob",
          "result": "true"
        }
      },
      {
        "Wild": {
          "System": "Wild",
          "result": "true"
        }
      },
      {
        "CRaft": {
          "System": "Craft",
          "result": "false"
        }
      }
    ]
  }
}

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