Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Json to Java Object

Tags:

java

json

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);
like image 560
ludwigmi Avatar asked Mar 20 '23 06:03

ludwigmi


2 Answers

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;
    }
}
like image 136
Manu Viswam Avatar answered Mar 22 '23 20:03

Manu Viswam


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.

like image 20
Karthik Surianarayanan Avatar answered Mar 22 '23 19:03

Karthik Surianarayanan