无法将JSON数据映射到Java对象

时间:2014-01-09 21:13:40

标签: java json gson

我在为以下JSON数据制定适当的java对象结构时遇到一些麻烦:

"pages": {
            "181382": {
                "pageid": 181382,
                "ns": 0,
                "title": "Anonymity"
            },
            "7181837": {
                "pageid": 7181837,
                "ns": 0,
                "title": "Anonymous"
            }
        }

标识符“181382”和“7181837”根据返回的数据而变化,因此这些标识符不能用作对象的成员。我尝试使用Map<String, Object>方法来处理它,但有点卡住了。

编辑: 这就是我试过的

public class PageData {

    int pageid;
    String ns;
    String title;

    public int getPageid() {
        return pageid;
    }

    public String getNs() {
        return ns;
    }

    public String getTitle() {
        return title;
    }

}



Map<String, PageData> pages = results.getPages().getData();

        for (PageData data : pages.values()) {
            System.out.println(data.getTitle());
        }

1 个答案:

答案 0 :(得分:1)

只需为您的Object创建一些包装器。这是一个有效的例子:

<强>包装

public class Wrapper {
    Map<String, PageData> pages = null;

    public Map<String, PageData> getPages() {
        return pages;
    }   
}

<强>启动

public class Launcher {
    public static void main(String[] args) {
        String str = "{\"pages\": {\r\n" + 
                "            \"181382\": {\r\n" + 
                "                \"pageid\": 181382,\r\n" + 
                "                \"ns\": 0,\r\n" + 
                "                \"title\": \"Anonymity\"\r\n" + 
                "            },\r\n" + 
                "            \"7181837\": {\r\n" + 
                "                \"pageid\": 7181837,\r\n" + 
                "                \"ns\": 0,\r\n" + 
                "                \"title\": \"Anonymous\"\r\n" + 
                "            }\r\n" + 
                "        }" +
                "}";


        Gson gson = new Gson();

        Wrapper results = gson.fromJson(str, Wrapper.class);

        Map<String, PageData> pages = results.getPages();

        for (PageData data : pages.values()) {
            System.out.println(data.getTitle());
        }
    }
}

<强> PageData

public class PageData{/* the same */}

输出:

Anonymity
Anonymous