Spring 控制器:如何将 json 反序列化为 Map<Object、Object>



我使用Unity向Spring服务器发送JSON。然而,我不知道如何反序列化这样一个复杂的对象。做这件事最干净的方法是什么?

我有这3个班:

public class Garden {
private Integer width;
private Integer height;
private Map<Position, Sprite> objects;
public Garden(Integer width, Integer height, Map<Position, Sprite> objects) {
this.width = width;
this.height = height;
this.objects = objects;
}
/* getters and setters */
}
public class Position {
private int x;
private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
/* getters and setters */
}
public class Sprite {
private String name;
private Boolean mirrored;
private Integer size;
public Sprite(String name, Boolean mirrored, Integer size) {
this.name = name;
this.mirrored = mirrored;
this.size = size;
}
/* getters and setters */
}

控制器内部的PostMapping方法:

@PostMapping
public ResponseEntity<Garden> postGarden(Garden garden) {
/* Doing things */
}

JSON是这种格式的

{
"objects":{
"(1, 1)":{
"name":"Box",
"size":1,
"mirrored":false
},
"(5, 7)":{
"name":"Water",
"size":1,
"mirrored":false
}
},
"width":10,
"height":10
}

这里,只有宽度和高度被成功传输,但是HashMap是空的。

你知道怎么解决吗?

Json的objectsMap<String, Sprite>,而您的是Map<Position, Sprite>

Json反序列化程序无法自动将String转换为Position

您可以为JSON库提供String->Position的自定义转换器(请参阅库的文档(,也可以尝试技巧JSON库


public class Garden {
private Integer width;
private Integer height;
private Map<Position, Sprite> objects;
public Garden(Integer width, Integer height, Map<Position, Sprite> objects) {
this.width = width;
this.height = height;
this.objects = objects;
}
public Map<Position, Sprite> getObjects() { return objects; }
public void setObjects(Map<Object, Sprite> objects) { 
this.objects = new HashMap<>(); 
for (Map.Entry e : objects.entrySet()) {
Object key = e.getKey();
Sprite sprite = e.getValue();
if (key instanceof String) {
Position position = convertToPosition(key);
this.objects.put(position, sprite);
} else if (key instanceof Position){
this.objects.put((Position)key, sprite);
} else {
throw new IllegaStateException(key);
}
}
}
}

但是,最好更改Garden对象结构

public class SpriteAtPosition {
private Position position;
private Sprite sprite;
...
}
public class Garden {
private Integer width;
private Integer height;
private List<SpriteAtPosition> sprites;
public Garden(Integer width, Integer height, List<SpriteAtPosition> sprites) {
this.width = width;
this.height = height;
this.sprites = sprites;
}

所以Json会成为

{
"objects":[
{
"position": {
"x": 1,
"y": 1,
},
"sprite": {
"name":"Box",
"size":1,
"mirrored":false
}
},
{
"position": {
"x": 5,
"y": 7,
},
"sprite": {
"name":"Water",
"size":1,
"mirrored":false
}
}
],
"width":10,
"height":10
}

最新更新