ludwigmi
ludwigmi

Reputation: 43

Parsing Json to Java Object

got this problem: Json:

{"authenticationToken":{"token":"c9XXXX1-XXXX-4XX9-XXXX-41XXXXX3XXXX"}}

Object:

    public class AuthenticationToken {
 public AuthenticationToken() {

 }

 public AuthenticationToken(String token) {
  authenticationToken = token;
 }

    @JsonProperty(value="token")
    private String authenticationToken;


 public String getAuthenticationToken() {
  return authenticationToken;
 }

 public void setAuthenticationToken(String authenticationToken) {
  this.authenticationToken = authenticationToken;
 }
}

But i got a a error in logs: Could not read JSON: Unrecognized field "authenticationToken" (class de.regalfrei.android.AuthenticationToken), not marked as ignorable (one known property: "token"]) and i do not have any idea how to set the JSON properties correct for this situation. Can someone help?

As you said i added a Wrapperclass:

public class AuthenticationTokenWrapper {
    AuthenticationToken authenticationToken;

    public AuthenticationTokenWrapper(AuthenticationToken authenticationToken) {
        this.authenticationToken = authenticationToken;
    }
    @JsonProperty(value="authenticationToken")
    public AuthenticationToken getAuthenticationToken() {
        return authenticationToken;
    }

    public void setAuthenticationToken(AuthenticationToken authenticationToken) {
        this.authenticationToken = authenticationToken;
    }

}

and called this function:

AuthenticationTokenWrapper tok =restTemplate.postForObject(url, requestEntity, AuthenticationTokenWrapper.class);

Upvotes: 4

Views: 667

Answers (3)

Manu Viswam
Manu Viswam

Reputation: 1646

You are using a wrapper class which have a variable named authenticationToken which is an object of AuthenticationToken

in order to parse your JSON correctly, create a wrapper class like this

public class Wrapper {
private AuthenticationToken authenticationToken;

public Wrapper(AuthenticationToken authenticationToken) {
    this.authenticationToken = authenticationToken;
}

public AuthenticationToken getAuthenticationToken() {
    return authenticationToken;
}

public void setAuthenticationToken(AuthenticationToken authenticationToken) {
    this.authenticationToken = authenticationToken;
    }
}

Upvotes: 6

Scary Wombat
Scary Wombat

Reputation: 44834

try

@JsonProperty(value="authenticationToken")
private String authenticationToken;

then un-marshall that string into another class with

@JsonProperty(value="token")
private String tokenStr;

Upvotes: 0

Karthik Surianarayanan
Karthik Surianarayanan

Reputation: 626

I am not sure about this...

Maybe the error is here private String authenticationToken; You are saying authenticationToken is a string, but according to the JSON Object it is another JSON Object. Try converting it into JSON Object and access the token.

Upvotes: 1

Related Questions