user2130951
user2130951

Reputation: 2741

Convert jsonnode to pojo

I can't get the json string that is sent to parse into the pojo.

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.sg.info.Account out of START_ARRAY token at [Source: java.io.StringReader@1f6dcfe2; line: 1, column: 1]

This is the json

[{"accno":9210255,"type":"Stock- and mutual funds account","default":true,"alias":"Karlsson Joachim"}]

The parsing

public void getAccounts()
    {
        ObjectMapper mapper = new ObjectMapper();
        String resp = Login.getBaseResource().path("accounts").request(Login.getResponsetype()).get(String.class);

        try  {

            account = mapper.readValue(resp, Account.class);

POJO

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
public class Account {

    public Account() {

    }
    private long accno;
    private String type;
    @JsonProperty("default")
    private String isDefault; 
    private String alias;


    public long getAccno() {
        return accno;
    }
    public void setAccno(long accno) {
        this.accno = accno;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getAlias() {
        return alias;
    }
    public void setAlias(String alias) {
        this.alias = alias;
    }
    @Override
    public String toString() {
        return "Account [accno=" + accno + ", type=" + type + ", alias="
                + alias + "]";
    }
    public String isDefault() {
        return isDefault;
    }
    @JsonProperty("default")
    public void setDefault(String isDefault) {
        this.isDefault = isDefault;
    }




}

Upvotes: 0

Views: 2779

Answers (1)

Uri Shalit
Uri Shalit

Reputation: 2308

The problem you have is the JSON you have is an array, and can have multiple accounts. If you change the parsing code to something like this, it will work:

    ObjectMapper mapper = new ObjectMapper();
    String str = "[{\"accno\":9210255,\"type\":\"Stock- and mutual funds account\",\"default\":true,\"alias\":\"Karlsson Joachim\"}]";

    JavaType accountListType =  mapper.getTypeFactory().constructArrayType(Account.class);

    Account[] accounts = SharedJsonSerializer.objectMapper().readValue(str, accountListType);

Of course it is better to use a collection type, you can construct any type you want using the mapper.getTypeFactory()

Upvotes: 1

Related Questions