简体   繁体   中英

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:

{
"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:

           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.

static fields are by default excluded from serialization/deserialization.

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.

Gson instantiates an instance of your class(es) from your JSON. After modifying your classes, you then will do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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