简体   繁体   English

使用GSON结构进行JSON解析

[英]JSON parsing with GSON Structure

I've tried to do this in another project, and as per the tutorials I've seen, I know I am on the right track, but I cannot get this parsing correctly: 我已经尝试在另一个项目中执行此操作,并且根据我所看到的教程,我知道自己处在正确的轨道上,但是我无法正确进行此解析:

(Much Simplified) JSON Output: (简化了)JSON输出:

{
"data":{
  "info":{
      "username": "something"
      "email" : "something"
   }
..
..

} }

I am trying to get "username" and "email using the following classes: 我正在尝试使用以下类来获取“用户名”和“电子邮件”:

class ProfileResponse {
static Data data;

public static Data getData() {
    return data;
}

public static void setData(Data data) {
    ProfileResponse.data = data;
}

} }

Class Data {
@SerializedName("info")
static Info info;

public static Info getInfo() {
    return info;
}

public static void setInfo(Info info) {
    Data.info = info;
}

} }

class Info {
@SerializedName("username")
static String username;
@SerializedName("email")
static String email;

public static String getUsername() {
    return username;
}

public static String getEmail() {
    return email;
}

}

and Deserializing the JSON String (could it be a problem that it's a String?) like so: 并反序列化JSON字符串(这是字符串的问题吗?),如下所示:

           Gson gson = new Gson();
                        gson.fromJson(response, ProfileResponse.class);
                        if (Info.getUsername() == null
                                || Info.getUsername().isEmpty()) {
                            System.out.println("NO USERNAME");
                        } else {
                            System.out.println("USERNAME: "
                                    + Info.getUsername());
                        }

This is printing "NO USERNAME" each time it's run. 每次运行时都在打印“ NO USERNAME”。

static fields are by default excluded from serialization/deserialization. 默认情况下, static字段不包括在序列化/反序列化中。

Remove all the static keywords from your classes (fields and methods), call fromJson() correctly, and you will then get the result you're looking for. 从您的类(字段和方法)中删除所有static关键字,正确地调用fromJson() ,然后您将得到想要的结果。

Gson instantiates an instance of your class(es) from your JSON. Gson从JSON实例化您的类的实例。 After modifying your classes, you then will do: 修改课程后,您将执行以下操作:

ProfileResponse pr = gson.fromJson(response, ProfileResponse.class); 

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

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