简体   繁体   中英

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 aa 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);

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

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.

try

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

then un-marshall that string into another class with

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

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