简体   繁体   中英

Gson.fromJson, how to use dynamic json value on my POJO class?

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 to handle (for exp: "18302") json key? 设置什么类来处理 (例如exp:“ 18302”)的json键?

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.

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"

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