JSON到java对象使用GSON [英] JSON to java object using gson

查看:170
本文介绍了JSON到java对象使用GSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用GSON库图灵自带形成一个Web服务JSON,但我不能让它工作,我总是得到一个空。我已经通过类似的问题,看起来像转换JSON来的Java,如简单的JSON到Java皈依使用GSON 。但我还是失去了一些东西。

I am using GSON library for turing JSON that comes form a web service but I can't make it work, I always get a null. I've looked through similar issues like Converting Json to Java such as Simple Json to Java convertion using GSON. But I am still missing something

JSON

{"A":"val1","B":"val2","C":"val3","D":"val4","E":"val5","F":"val6","G":"val7"}
         SiteWrapper m = gson.fromJson(json, SiteWrapper.class);

Java类

SiteWrapper m = gson.fromJson(json, SiteWrapper.class);
System.out.println(m.getMenu());

static class Site {
    static String A;
    static String B;
    static String C;
    static String D;
    static String E;
    static String F;
    static String G;

    public String toString() {
        return String.format(A,B,C,D,E,F,G);}

    public static String getA() {
        return A;
    }
    public static String getB() {
        return B;
    } 
... all the way to getG

    public void setA(String A) {
        Site.A = A;
    }
    public void setB(String B) {
        Site.B = B;
    }
... all the way to setB

和我的包装

class SiteWrapper {
    private Site site;
    public Site getMenu() { return site; }
    public void setMenu(Site site) { this.site = site; }
}

不管我做什么,我得到印空,任何想法?

no matter what I do I get a null printed , any ideas?

推荐答案

自一个静态内部类。作为的文档指出和评论:

Since its a static inner class .As docs pointed out and comments :

同样,如果一个字段被标记为静态,那么在默认情况下它会
  排除。如果你想加入一些短暂的领域...

As well, if a field is marked as "static" then by default it will be excluded. If you want to include some transient fields...

您可能想尝试

 Gson gson = new GsonBuilder()
    .excludeFieldsWithModifier()
    .create();

此外,由于它是一个内部类,你可能需要改变你的JSON如果您可以:

Also, since its a inner class you may need to change your JSON If you can:

 {
   "site":{
      "A":"val1",
      "B":"val2",
      "C":"val3",
      "D":"val4",
      "E":"val5",
      "F":"val6",
      "G":"val7"
   }
}

由于这里要注意在这个<一个href=\"http://stackoverflow.com/questions/4470339/deserializing-arbitrary-object-json-arrays-in-inner-classes-with-gson-or-nested\">post

这篇关于JSON到java对象使用GSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆