简体   繁体   English

使用Gson将json字符串解析为对象

[英]Parse json string to object using Gson

I tried converting my json string to java object by using Gson but somehow it was not successful and I haven't figured out why.. 我尝试通过使用Gson将json字符串转换为java对象,但不知何故,我也没弄清楚原因。

My Json string 我的Json琴弦

{
    "JS":{
        "JS0":{
            "Name":"ABC",
            "ID":"5"
        },
        "JS1":{
            "Location":"UK",
            "Town":"LD"
        },
        "JS2":{
            "Usable":"true",
            "Port":"ABC"
        }
    }
}

In java code I have 4 classes, JS, JS0, JS1 and JS2 在Java代码中,我有4个类,JS,JS0,JS1和JS2
JS class contains JS0, JS1 and JS2 variables JS类包含JS0,JS1和JS2变量
JS0, JS1 and JS2 classes contain fields as in Json string example, eg JS0 contains 02 fields, String Name and String ID JS0,JS1和JS2类包含与Json字符串示例相同的字段,例如JS0包含02个字段,字符串名称和字符串ID
In all classes I have getter/setter for variables, 02 constructors (01 with empty parameters and another one with all variables in the parameter field) 在所有类中,我都有变量的getter / setter,02个构造函数(01个带有空参数,而另一个带有参数字段中的所有变量)


And for using Gson: 对于使用Gson:

Gson gson = new Gson();
jsObject = gson.fromJson(sb.toString(), JS.class);


When I access JS0, JS1 and JS2 objects from jsObject, they are null... 当我从jsObject访问JS0,JS1和JS2对象时,它们为null。
Can someone show me what did I do wrong? 有人可以告诉我我做错了什么吗?
Thank you very much, 非常感谢你,

The problem here is, you are trying to convert 这里的问题是,您正在尝试转换

{
   "JS" : {
       /* rest of JSON */
   }
}

to JS object, but the above JSON is a representation of Java class like this JS对象,但是上面的JSON是这样的Java类的表示

class Foo {
   JS JS;
}

So, you need to get the value of JS from the JSON string first, then call fromJSON to deserialize it with the JS.class passed as the second parameter. 因此,您需要首先从JSON字符串中获取JS的值,然后调用fromJSON以将JS.class作为第二个参数传递来反序列化它。

OR 要么

Create a simple class containing only JS as a variable, then call fromJSON with that class passed as the second parameter of fromJSON like this: 创建一个仅包含JS作为变量的简单类,然后调用fromJSON并将该类作为fromJSON的第二个参数传递,如下所示:

Java Java的

class Foo {
   JS JS;
}


jsObject = gson.fromJson(sb.toString(), Foo.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM