[英]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:我的 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
.您需要为Monobank
中的字段定义 setter 方法。 Or you could declare the fields as public
.或者您可以将这些字段声明为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
.或者,如果您使用的是lombok
,只需使用@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.这是必需的,因为在解析 json 时,使用适当的 setter 方法将值设置为每个字段,或者如果字段是public
,则直接设置值。 Otherwise the parsing would fail.否则解析会失败。
I do not recommend using public
fields.我不建议使用public
领域。 The fields should be modified via a setter method, which is the standard approach.这些字段应该通过标准方法的 setter 方法进行修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.