Search code examples
javajsongsonpojo

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.


Solution

  • 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;