我必须从我的json文件中创建java对象,看起来像这样:{“colors”:[“red”,“绿色”,“blue”],“isPrimary”:true,“rgb”:{“r”:255,“g”:0,“B”:0 } }
我创建了一个带有参数的类来描述我的文件
public class Color {
private List<String> colors;
private boolean isPrimary;
private HashMap<String,Integer> rgb = new HashMap<String,Integer>();
public Color(){};
public List<String> getColors() {
return colors;
}
public void setColors(List<String> colors) {
this.colors = colors;
}
public boolean isPrimary() {
return isPrimary;
}
public void setPrimary(boolean primary) {
isPrimary = primary;
}
public HashMap<String, Integer> getRgb() {
return rgb;
}
public void setRgb(HashMap<String, Integer> rgb) {
this.rgb = rgb;
}
@Override
public String toString() {
return "Color{" +
"colors=" + colors +
", isPrimary=" + isPrimary +
", rgb=" + rgb +
'}';
}
}
主要类别:
public static void main(String[] args) throws JsonProcessingException {
String jsonStr = "{\r\n" +
" \"colors\": [\"red\", \"green\", \"blue\"],\r\n" +
" \"isPrimary\": true,\r\n" +
" \"rgb\": {\r\n" +
" \"r\": 255,\r\n" +
" \"g\": 0,\r\n" +
" \"b\": 0\r\n" +
" }\r\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
Color color = objectMapper.readValue(jsonStr, Color.class);
System.out.println(color);
}
我是按照指示做的,但可能出了什么问题
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "isPrimary" (class itstep.task_5.Color), not marked as ignorable (3 known properties: "colors", "primary", "rgb"])
at [Source: (String)"{
"colors": ["red", "green", "blue"],
"isPrimary": true,
"rgb": {
"r": 255,
"g": 0,
"b": 0
}
}";
2条答案
按热度按时间3xiyfsfu1#
问题是JSON字段名是
isPrimary
,而Java字段名是primary
。要解决此问题,您可以将JSON字段名称更改为
primary
,或者向Java字段添加@JsonProperty
注解,以指定它应Map到isPrimary
JSON字段名称:输出:
fnvucqvd2#
你的setter和getter有错误的名字。Jackson试图使用格式为
set{fieldname}
的setter方法来赋值,例如setIsPrimary
。但是你的setter被称为setPrimary
,所以你的类的属性“isPrimary”(属性由同名的getter和setter标识)找不到。这就是Exception试图告诉你的。TL;DR:将
setPrimary
方法重命名为setIsPrimary
。