1

I have the data below and I'm trying to read the data and allocate each in variables but can not get the data in the info, still giving me null or blank for email and phone

    {
    "_id": ObjectId ( "56c570d904df6c51b463da54"),
    "Name": "John Smith"
    "Age": 31,
    "Info": {
        "Email", "[email protected]"
        "Phone", "+987654321"
    }
}

below the java code

findAll.forEach (new Block <Document> () {

                @Override
                public void apply (Document document) {
                    String name = document.getString ( "name")!= null? document.getString ( "name"): "";
                    int age = document.getInteger ( "age")!= null? document.getInteger ( "age"): 0;
                    String email = document.getString ( "info.email")!= null? document.getString ( "info.email") "";
                    String phone = document.getString ( "info.phone")! = null? document.getString ( "info.phone") "";
                    Costumer costumer = new Costumer (name, age, email, phone);
                    System.out.println (costumer);
                }
            });

1 Answer 1

2

That looks close! There are a couple bugs in the code:

  1. change Null to null
  2. You cannot lookup nested keys eg: document.getString( "info.email") will not work. You should assign the sub document to a variable and then try and get the data out of it.

I haven't tested it but I think something like this should work better:

findAll.forEach (new Block <Document> () {
    @Override
    public void apply (Document document) {
        String name = document.getString ("name")! = null? document.getString( "name") : "";
        int age = document.getInteger ( "age", 0);

        // Get the info subdocument
        Document info = document.get("info", Document.class);
        String email = "";
        String phone = "";
        if (info != null) {
          email = info.getString ("email")! = null? info.getString("email") : "";
          phone = info.getString ("phone")! = null? info.getString("phone") : "";
        }
        Costumer costumer = new Costumer (name, age, email, phone);
        System.out.println(costumer);
    }
});

Hope that helps.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked, just a little change from your solution, thank you email = info.getString ("email")! = null? info.getString("email") : ""; phone = info.getString ("phone")! = null? info.getString("phone") : "";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.