0

I have a Json structure like so:

{
   "Pojo" : {
       "properties" : {
          "key0" : "value0",
          "key1" : "value1"
       }
   }
}

I want my final result to look something like this:

public class Pojo {
     public Map<String, String> properties;
}

but instead I get something like this:

public class Pojo {
   public Properties properties;
}

public class Properties {
  public String key0;
  public String key1;
}

Right now all I am doing for parsing the Json is this:

new Gson().fromJson(result, Pojo.class)

Thoughts on what I would need to do to get this set up correctly? I do not have the ability to change the Json return object's structure.

2 Answers 2

2

Gson is trying to match the JSON field name to a POJO field, so you above JSON is implying the top level object has a field named 'Pojo'. In fact, it is indicating the following class structure,

class Container {
    MyObject Pojo;
}

class MyObject {
    Map<String, String> properties;
}

where the name of the classes MyObject and Container are completely arbitrary. Gson matches field names, not object type names.

You can deserialize that object with a simple statement -

Container container = gson.fromJson(result, Container.class);

Your map with then be container.Pojo.properties

If you would rather not have the extra container class, you can parse to a Json tree first, and then extra the part that you an interested in --

JsonElement json = new JsonParser().parse(result);
// Note "Pojo" below is the name of the field in the JSON, the name 
// of the class is not important
JsonElement pojoElement = json.getAsJsonObject().get("Pojo");
Pojo pojo = gson.fromJson(pojoElement, Pojo.class);

Then your map is in pojo.properties, which is what I think you want. I have left off error checking for clarity, but you will probably want to add some.

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

1 Comment

Thanks for helping me understand what Gson is trying to do here. This is my first attempt with the parser.
0

Try this:

JSONObject obj1=new JSONObject(jsonString);
JSONObject obj2=obj1.getJSONObject("Pojo");
JSONObject obj3=obj2.getJSONObject("properties");
String key1=obj3.getString("key0");
String key2=obj3.getString("key1");

For more reference try the link:

https://androidbeasts.wordpress.com/2015/08/04/json-parsing-tutorial/

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.