package com.example;
...
public abstract class Shape {
}
public class Triangle extends Shape {
...
}
public class Square extends Shape {
...
}
public class ListOfShape {
public List<Shape> shapes;
...
}
package com.example;
...
public abstract class Shape {
}
public class Triangle extends Shape {
...
}
public class Square extends Shape {
...
}
public class ListOfShape {
public List<Shape> shapes;
...
}
Copy to ClipboardCopied!Toggle word wrapToggle overflow
您可以实例化并序列化一个格式数组列表(ListOfShape),如下所示:
ObjectMapper objectMapper = new ObjectMapper();
ListOfShape shapeList = new ListOfShape();
shapeList.shapes = new ArrayList<Shape>();
shapeList.shapes.add(new Triangle());
shapeList.shapes.add(new Square());
String serialized = objectMapper.writeValueAsString(shapeList);
ObjectMapper objectMapper = new ObjectMapper();
ListOfShape shapeList = new ListOfShape();
shapeList.shapes = new ArrayList<Shape>();
shapeList.shapes.add(new Triangle());
shapeList.shapes.add(new Square());
String serialized = objectMapper.writeValueAsString(shapeList);
Copy to ClipboardCopied!Toggle word wrapToggle overflow
但是,接收器中现在存在一个问题。您可以通过将 type 指定为 readValue () 的第二个参数来告知接收器预期 ListOfShape 对象:
MyClass myobject = objectMapper.readValue(serialized, ListOfShape.class);
ObjectMapper objectMapper = new ObjectMapper();
MyClass myobject = objectMapper.readValue(serialized, ListOfShape.class);
ObjectMapper objectMapper = new ObjectMapper();
Copy to ClipboardCopied!Toggle word wrapToggle overflow