Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonMappingException: Unexpected token (START_OBJECT)

Tags:

java

json

jackson

I'm having problem with the user of Codehaus Jackson. I have an object with the next attributes and mapper declaration:

public class AuthenticatedPrincipal implements Serializable, Principal {
      @JsonIgnore
      private final static ObjectMapper mapper = new ObjectMapper().enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY).enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL)
      .setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL).setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);

  private String name;

  private Collection<String> roles;

  private Collection<String> groups;

  private boolean adminPrincipal;
...
  @JsonIgnore
  public String serialize() {
    try {
      return mapper.writeValueAsString(this);
    } catch (IOException e) {
      throw new RuntimeException("Unable to serialize Principal:" + toString(), e);
    }
  }

  @JsonIgnore
  public static AuthenticatedPrincipal deserialize(String json) {
    try {
      return mapper.readValue(json, AuthenticatedPrincipal.class);
    } catch (IOException e) {
      throw new RuntimeException("Unable to serialize Principal:" + json, e);
    }
  }
}

That is used from another class:

public class AuthRequest {

  @Transient
  private AuthenticatedPrincipal principal;
  @PreUpdate
  @PrePersist
  public void encodePrincipal() {
    if (principal != null) {
        this.encodedPrincipal = principal.serialize();
    }
  }

  @PostLoad
  @PostPersist
  @PostUpdate
  public void decodePrincipal() {
    if (StringUtils.isNotBlank(encodedPrincipal)) {
        this.principal = AuthenticatedPrincipal.deserialize(encodedPrincipal);
    }
  }
}

When I execute the funtionality that generate a String like this:

Principal:{"adminPrincipal":false,"displayName":"sdfas","groupAware":false,"name":"sdfas"}

When the method AuthenticatedPrincipal.deserialize(encodedPrincipal); is called parsing a Json parameter but that method fail with this error:

org.codehaus.jackson.map.JsonMappingException: Unexpected token (START_OBJECT), expected START_ARRAY: need JSON Array to contain As.WRAPPER_ARRAY type information for class com.trent.app.lib.principal.AuthenticatedPrincipal
 at [Source: java.io.StringReader@40fa255; line: 1, column: 1]

Can anyone help me?

like image 806
gleX Avatar asked May 28 '26 19:05

gleX


1 Answers

Principal:{"adminPrincipal":false,"displayName":"sdfas","groupAware":false,"name":"sdfas"}

Is not valid JSON. It needs to look like this

{"adminPrincipal":false,"displayName":"sdfas","groupAware":false,"name":"sdfas"}

(without the Principal: at the start)

like image 191
Simon Avatar answered May 30 '26 09:05

Simon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!