简体   繁体   中英

Serializing JSON string to object

I am trying to parse through a JSON string and convert it to the following POJO:

package apicall;
//POJO representation of OAuthAccessToken
public class OAuthAccessToken {
    private String tokenType;
    private String tokenValue;
    public OAuthAccessToken(String tokenType,String tokenValue) {
        this.tokenType=tokenType;
        this.tokenValue=tokenValue;
    }

    public String toString() {
        return "tokenType="+tokenType+"\ntokenValue="+tokenValue;

    }

    public String getTokenValue() {
        return tokenValue;
    }

    public String getTokenType() {
        return tokenType;
    }

}

In order to do this I have written the following code:

Gson gson=new Gson();
String responseJSONString="{\"access_token\" : \"2YotnFZFEjr1zCsicMWpAA\",\"token_type\" : \"bearer\"}";
OAuthAccessToken token=gson.fromJson(responseJSONString, OAuthAccessToken.class);
System.out.println(token);

When I run the code, I get the following output:

tokenType=null
tokenValue=null

Instead of 
tokenType=bearer
tokenValue=2YotnFZFEjr1zCsicMWpAA

I don't understand if there's anything I've done wrong. Please help.

You can get the expected result by annotating your fields like:

@SerializedName("token_type")
private final String tokenType;
@SerializedName("access_token")
private final String tokenValue;

How is Gson supposed to know how to populate your object? You don't have a no-arg constructor, and the fields of your object don't match the fields in the JSON object.

Make your object as following:

public class OAuthAccessToken {
    private String accessToken;
    private String tokenType;

    OAuthAccessToken() {
    }

    ...
}

The class should have the exact field name as the json, so if your json have 2 keys: "access_token" and "token_type", the class should have 2 fields:

private String access_token;
private String token_type;

And, of course you need to change the getters/setters accordingly.

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