杰克逊@JsonCreator无法识别的财产 [英] Unrecognised Property with Jackson @JsonCreator
问题描述
我正在尝试使用Jackson将一些JSON转换为包含一些简单Strings和另一个类的类的实例,而我正在使用@JsonCreator.看来Jackson不能创建另一个类的实例.
I'm trying to use Jackson to convert some JSON into an instance of a class that contains some simple Strings and another class, which I'm using @JsonCreator for. It seems that Jackson isn't able to create the instance of the other class.
问题是,当我在测试中运行此代码时:
The problem is that when I run this code as part of a test:
ObjectMapper mapper = new ObjectMapper();
Player player = mapper.readValue(json.toString(), Player.class);
我收到以下异常:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "characterClass" (class xxx.xxx.Player), not marked as ignorable (2 known properties: "name", "character"])
我要在简单测试中解析的JSON看起来像这样:
The JSON I'm trying to parse in my simple test looks like this:
{
"name": "joe",
"characterClass": "warrior",
"difficulty": "easy",
"timesDied": 2
}
我有一个看起来像这样的玩家"类
I have a class 'Player' that looks a bit like this
public class Player {
@JsonProperty("name")
private String playerName;
@JsonProperty // <-- This is probably wrong
private Character character;
// Some getters and setters for those two fields and more
}
还有另一个看起来像这样的字符"类
And another class 'Character' that looks like this
public class Character{
private PlayerClass playerClass;
private Difficulty difficulty;
private int timesDied;
@JsonCreator
public Character(@JsonProperty("characterClass") String playerClass,
@JsonProperty("difficulty") String diff,
@JsonProperty("timesDied") int died) {
// Validation and conversion to enums
this.playerClass = PlayerClass.WARRIOR;
this.difficulty = Difficulty.EASY;
this.timesDied = died;
}
// Again, lots of getters, setters, and other stuff
}
对于像这样的少量数据,将有更好的方法来构建整个结构,但是我认为这只是出于示例的目的.我拥有的实际代码更加复杂,但我想举一个简单的例子.
For small sets of data like this there would be better ways to structure the whole thing, but I think this works for the purposes of an example. The real code I have is more complex but I wanted to make simple example.
我认为我已经弄乱了Jackson的注解,但是我不确定自己做错了什么.
I think I've messed up the Jackson annotations, but I'm not sure what I've done wrong.
推荐答案
您需要在Player
上指定与您的JSON输入匹配的创建者.例如:
You need to specify a creator on Player
that matches your JSON input. For example:
@JsonCreator
public static Player fromStringValues(@JsonProperty("name") String name,
@JsonProperty("characterClass") String characterClass,
@JsonProperty("difficulty") String difficulty,
@JsonProperty("timesDied") Integer timesDied) {
Player player = new Player();
player.setPlayerName(name);
player.setCharacter(new Character(characterClass, difficulty, timesDied));
return player;
}
旁注,您可以像 this 那样构造枚举,而Jackson将为您完成从字符串到枚举的转换
A side note, you can structure your enums like this and Jackson will do the conversion from string to enum for you.
这篇关于杰克逊@JsonCreator无法识别的财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!