简体   繁体   中英

Unrecognized field while parsing JSON using Jackson

When I try to parse the string, I get an exception. Tried several solutions but none helped solve the problem. Below I will add the code, my dependency file, and an exception message.

package com.example;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Arrays;
import java.util.List;

public class ParserByJackson{
    private ObjectMapper mapper = new ObjectMapper();
    private List<Monobank> userList;

    public void parseJSON(String json){
        try {
            userList = Arrays.asList(mapper.readValue(json, Monobank[].class));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public List<Monobank> getUserList() {
        return userList;
    }
    static class Monobank{
        String currencyCodeA;
        String currencyCodeB;
        String date;
        String rateBuy;
        String rateSell;
    }
}

My pom xml:

<dependencies>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
</dependencies>

Error that I got:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "currencyCodeA" (class com.example.lab2.model.parsers.ParserByJackson$Monobank), not marked as ignorable (0 known properties: ])
 at [Source: (String)"[{"currencyCodeA":840,"currencyCodeB":980,"date":1615807806,"rateBuy":27.57,"rateSell":27.7701},{"currencyCodeA":978,"currencyCodeB":980,"date":1615801806,"rateBuy":32.82,"rateSell":33.2204}]

You need to have setter methods defined for the fields in Monobank . Or you could declare the fields as public .

static class Monobank{
    String currencyCodeA;
    String currencyCodeB;
    String date;
    String rateBuy;
    String rateSell;

    public void setCurrencyCodeA(String currencyCodeA) {
        this.currencyCodeA = currencyCodeA;
    }

    // similar setters for all other fields.
}

Or if you are using lombok , just annotate with @Setter .

This is required because while parsing the json, the values are set to each of the fields using the appropriate setter method or if the field is public , the the value is set directly. Otherwise the parsing would fail.

I do not recommend using public fields. The fields should be modified via a setter method, which is the standard approach.

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