无法将Json字符串反序列化为POJO(使用GSON)

时间:2011-08-26 20:59:13

标签: json gson deserialization

知道为什么JSON不会映射到java对象?

代码..

String result = "{\"outerclass\":{\"innerclass\":{\"booleanA\":true,\"stringB\":\"b\",\"stringC\":\"c\"}}}\n";

Gson gson = new Gson();
TempObject o = gson.fromJson(result,TempObject.class);

POJO ..

  public class TempObject {

     public static class outerclass {

      public static class innerclass {

       public static boolean booleanA;
       public static String stringB;
       public static String stringC;

      }    

     }

    }

OTher示例..

String result = "{\"idata\":{\"result\":{\"error\":true,\"errorMessage\":\"Invalid username and/or password\",\"requestTime\":\"2011-08-26T18:39:02Z\"}}}"; 
Gson gson = new Gson();
UserData d = gson.fromJson(result, UserData.class);

类..

public class UserData {

    idata data;

    public static class idata {
        result res;

        public static class result {

            public boolean error;
            public String errorMessage;
            public String requestTime;
        }    
    }
}

2 个答案:

答案 0 :(得分:0)

如果我没有记错的话,那是因为你的所有字段都是静态的,那些字段与每个单独的对象无关。

所以我认为课程应该是这样的:

public class TempObject {

    Outerclass outerclass;

    public static class Outerclass {
        Innerclass innerclass;

        public static class Innerclass {

            public boolean booleanA;
            public String stringB;
            public String stringC;
        }    
    }
}

例如,在我的机器上,输出:

public class Example{
    public static void main(String[] args)  {
        String result = "{\"outerclass\":{\"innerclass\":{\"booleanA\":true,\"stringB\":\"b\",\"stringC\":\"c\"}}}\n";
        Gson gson = new Gson();
        TempObject o = gson.fromJson(result, TempObject.class);
        System.out.println(gson.toJson(o));
    }

    public static class TempObject {

        Outerclass outerclass;

        public static class Outerclass {
            Innerclass innerclass;

            public static class Innerclass {

                public boolean booleanA;
                public String stringB;
                public String stringC;
            }    
        }
    }
}

时:

{"outerclass":{"innerclass":{"booleanA":true,"stringB":"b","stringC":"c"}}}

答案 1 :(得分:0)

您无法反序列化,因为变量名称与Json中的键不匹配。在你的第二个例子中

String result = "{\"idata\":{\"result\":{\"error\":true,\"errorMessage\":\"Invalid username and/or password\",\"requestTime\":\"2011-08-26T18:39:02Z\"}}}"; 

idata data;
result res;

对象名称应与JSON中的键匹配,但不能与类名匹配。

IData idata ; 结果结果;