Код ошибки:
Исключение в потоке «main» com.fasterxml.jackson.databind.exc.InvalidTypeIdException: не удалось разрешить введите идентификатор 'IItem;' как подтип items.IItem[]: известные идентификаторы типов = [Diamond, Grass, Sword] (для свойства POJO «инвентарь»)
`import items.Grass;
import items.IItem;
import java.io.IOException;
public class Main {
Код: Выделить всё
public static void main(String[] args) throws IOException {
Player player = new Player(new IItem[][]{{new Grass(5, 2)}},12,20);
player.print();
System.out.println();
String data = player.write();
System.out.println(data);
System.out.println();
Player player2 = Player.read(data);
player2.print();
}
Код: Выделить всё
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import items.Diamond;
import items.Grass;
import items.IItem;
import items.Sword;
import java.io.IOException;
public class Player {
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = Grass.class, name = "Grass"),
@JsonSubTypes.Type(value = Sword.class, name = "Sword"),
@JsonSubTypes.Type(value = Diamond.class, name = "Diamond")
})
private IItem[][] inventory;
private int health;
private int maxHealth;
public Player() {
}
@JsonCreator
public Player(
@JsonProperty("inventory") IItem[][] inventory,
@JsonProperty("health") int health,
@JsonProperty("maxHealth") int maxHealth) {
this.inventory = inventory;
this.health = health;
this.maxHealth = maxHealth;
}
public void print() {
System.out.println("Player=h" + health + ",m" + maxHealth);
System.out.println("Inventory has:");
for (int i = 0; i < inventory.length; i++) {
for (int j = 0; j < inventory[i].length; j++) {
if (inventory[i][j] != null) {
System.out.print(" - ");
inventory[i][j].print();
}
}
}
}
public String write() throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(this);
}
public static Player read(String data) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(data, Player.class);
}
public IItem[][] getInventory() {
return inventory;
}
public void setInventory(IItem[][] inventory) {
this.inventory = inventory;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getMaxHealth() {
return maxHealth;
}
public void setMaxHealth(int maxHealth) {
this.maxHealth = maxHealth;
}
}
Я пробовал делать аннотации, но они помогают только в случае с 1 объектом, и при
обычной матрице объектов (инвентарь IItem[]).
Подробнее здесь: https://stackoverflow.com/questions/787 ... using-json
Мобильная версия