Java 动态响应行的Json反序列化程序
使用Java 动态响应行的Json反序列化程序,java,json,gson,Java,Json,Gson,使用GSON,为如下所示的pojo生成json响应的反序列化器是正确的方法吗 { user: "me", red: {"some object"}, green: {...} ... .... ..... } 我想我需要一个像这样的东西 class ColorResponse { String user; Map<String, Color> colorMap; } 类颜色响应{ 字符串用户; 地图彩色地
GSON
,为如下所示的pojo生成json响应的反序列化器是正确的方法吗
{
user: "me",
red: {"some object"},
green: {...}
...
....
.....
}
我想我需要一个像这样的东西
class ColorResponse {
String user;
Map<String, Color> colorMap;
}
类颜色响应{
字符串用户;
地图彩色地图;
}
我担心您试图实现的解决方案是不可能的,因为colorMap
不是JSON的属性,JSON应该是
{
user: "me",
colorMap: {
red: {"some object"},
green: {...}
...
}
}
然后,您现在需要的是一个自定义反序列化器,它迭代响应的JSONObject。这是如何使用自定义代码和GSON进行反序列化的一个很好的示例
基本上,您必须为ColorResponse类注册一个自定义反序列化程序,您可以执行以下操作:
deserialize() {
ColorResponse response = new ColorResponse();
List<Color> colors = new ArrayList<>();
response.setName(json.getAsJsonObject().get("name").asString());
for (Entry<String, JsonElement> entry : json.entrySet()) {
if (!entry.getKey().equals("name")) {
colors.add(new Color(entry.getKey(), entry.getValue()));
}
}
}
反序列化(){
ColorResponse=新的ColorResponse();
列表颜色=新的ArrayList();
response.setName(json.getAsJsonObject().get(“name”).asString());
for(条目:json.entrySet()){
如果(!entry.getKey().equals(“name”)){
添加(新颜色(entry.getKey(),entry.getValue());
}
}
}
这段代码只是为了说明如何做到这一点,我已经在飞行中编写了它,我不确定它是否会编译,但关键是如果你只拥有这个名称,那么它将是常量,其余的都是颜色,然后只需将所有颜色添加到列表、贴图或任何你想要的东西中。所以我的解决方案是自定义反序列化程序
public class ColorDeserializer implements JsonDeserializer<ColorResponse> {
private List<String> colors;
public ColorDeserializer(List<String> colors) {
this.colors = colors;
}
@Override
public ColorResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject object = json.getAsJsonObject();
long timestamp = object.get("timestamp").getAsLong();
String username = object.get("user").getAsString();
ColorResponse colorResponse = new ColorResponse(timestamp, username);
for (String color: colors) {
JsonObject jsonObject = object.get(color).getAsJsonObject();
if (jsonObject != null) {
colorResponse.getColorMap().put(color, context.<Color>deserialize(jsonObject, Color.class));
}
}
return colorResponse;
}
}
公共类ColorDeserializer实现JsonDeserializer{
私有列表颜色;
公共颜色反序列化程序(列出颜色){
这个。颜色=颜色;
}
@凌驾
公共ColorResponse反序列化(JsonElement json,类型typeOfT,JsonDeserializationContext)引发JsonParseException{
JsonObject object=json.getAsJsonObject();
long timestamp=object.get(“timestamp”).getAsLong();
字符串username=object.get(“用户”).getAsString();
ColorResponse ColorResponse=新的ColorResponse(时间戳、用户名);
用于(字符串颜色:颜色){
JsonObject JsonObject=object.get(color.getAsJsonObject();
if(jsonObject!=null){
colorResponse.getColorMap().put(color,context.deserialize(jsonObject,color.class));
}
}
返回颜色响应;
}
}
该JSON是您的还是您从其他地方收到的?它是后端遗留格式,因此我无法更改它=(