0

gson class:

import com.google.gson.*;

myJson:

{
"time": "notime",
"query": {
     "pages": {
         "18302": {
             "title": "Car",
             "pagelanguage": "en"
         }
      }
}
}

Custom POJO class:

public class MyClass {
    public String time;
    public Query query;

    public class Query {
        public ? pages;

        //...
    }
}

Java code:

Gson gson = new GsonBuilder().create();
MyClass data = gson.fromJson(myJson, MyClass.class);

What Class should i set to my "pages" variable to handle dynamically changing (for exp: "18302") json key?

7
  • Is the value of pages known? In other words, will it always be a JSON object with title and pagelanguage? Commented Mar 21, 2015 at 1:15
  • yes, the only chancing variable name is "18302" Commented Mar 21, 2015 at 1:17
  • 1
    Then I would use a Map with the value type being a POJO type that fits the JSON object with title and pagelanguage. Commented Mar 21, 2015 at 1:18
  • in fact, the "18302" can have a custom class too (like Query), so if i use Map than i lost the pojo tree. And i can't access to my custom class in "18302"? Commented Mar 21, 2015 at 1:25
  • Right, you'll have to check the keys. Commented Mar 21, 2015 at 1:28

2 Answers 2

2

You could use a Map.

public class MyClass {
    public String time;
    public Query query;

    public static class Query {
        public Map<String, Page> pages; // <-- here

        public static class Page {
            public String title;
            public String pagelanguage;
        }
    }
}

"18302": {...} will be stored as an entry in the Map with the key being "18302" and the value being a new Page object.

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

Comments

1

If you don't want to create a Page class, this will work:

Map<String, Map<String, String>> pages;

Then to use it:

pages.get("18302").get("title") // "Car"

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.