0

I have the following JSON String extracted fro MongoDB:

{ "_id" : { "$oid" : "552645a5d3d57a6fc594c3c6"} , "name" : "mark" , 
"Info" : { "age" : 18 , "email" : "[email protected]" , "phone" : "321-456-778"}}

I'm trying to map the above JSON to the following class:

public class User {

    String name;
    Info info;

    // Getters/Setters
    public User(String name, int age, String email, String phone) {
        this.name = name;
        this.info = new Info(age, email, phone);
    }


    static class Info{

        public Info(int age, String email, String phone) {
            super();
            this.email = email;
            this.phone = phone;
            this.age = age;
        }

        public Info( ) {
        }

        String email;
        String phone;
        int age;
        // Getters/Setters

    }
}

By using the fromJson method of Gson:

Gson gson = new Gson();
User u = gson.fromJson(jsonString, User.class);

The resulting User has a null Info attached to it. Any idea how to fix it?

2
  • please check your class implementation, here class name is User and constructor is for Customer and next class name is User and constructor is for Info Commented Apr 9, 2015 at 10:15
  • beg your pardon. Did some mess with the editor. Now I have corrected it Commented Apr 9, 2015 at 10:28

1 Answer 1

1

The problem is in Json. Actually this Json is following mix naming strategy.

the "info" object is coming in camel case and others are coming in small case. thats why it is difficult for gson to convert it into Object.

If you can convert all keys into lower then your code will work fine. If you want all your keys to be in camel case then you can use GsonBuilder to configure naming policy.

E.g :

GsonBuilder builder=new GsonBuilder();

builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);

Gson g=builder.create();

but for your case a simple work-around would be to convert info object into lower case i.e. your converted json will be :

{ "_id" : { "$oid" : "552645a5d3d57a6fc594c3c6"} , "name" : "mark" , 
"info" : { "age" : 18 , "email" : "[email protected]" , "phone" : "321-456-778"}}
Sign up to request clarification or add additional context in comments.

Comments

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.