简体   繁体   English

使用gson解析JSON数组中的多种类型

[英]Parsing multiple types in a JSON array with gson

I am attempting to parse a JSON string using a POJO with gson, I have run into a snag however when attempting to read the following JSON array: 我正在尝试使用带有gson的POJO解析JSON字符串,但是在尝试读取以下JSON数组时遇到了一个障碍:

{"translate":"chat.type.text","with":[{"insertion":"woder22","clickEvent":{"action":"suggest_command","value":"/msg woder22 "},"hoverEvent":{"action":"show_entity","value":"{name:\"woder22\",id:\"bbd02ce0-24de-4683-8c8f-5d7e6b7dffa6\",}"},"text":"woder22"},"hi"]}

Everything works just fine until I get to the "with" part, I am trying to parse it by using the following POJOs 一切正常,直到我进入“ with”部分,我正在尝试通过使用以下POJO进行解析

public class ChatMessage {
    private String text = "";
    private String translate;
    private List<With> with = new ArrayList<With>();
    private String score;
    private String selector;
    private List<Node> extra;
    private String bold = "false";
    private String italic = "false";
    private String underlined = "false";
    private String strikethrough = "false";
    private String obfuscated = "false";
    private String color;
    private Clicked clickEvent;
    private Hover hoverEvent;
    private String insertion;

    //getter and setter method here

}

class Node {
    private String color;
    private String text;

    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
}

class Clicked {
    private String action;
    private String value;

    public String getAction() {
        return action;
    }
    public void setAction(String action) {
        this.action = action;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
}

class Hover {
    private String action;
    private String value;

    public String getAction() {
        return action;
    }
    public void setAction(String action) {
        this.action = action;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
}

I have changed this to show all of the code 我已经更改了它以显示所有代码

public class With {
    private String translate;
    private Clicked clickEvent;
    private Hover hoverEvent;
    private String insertion;
    private String text = "";

    //setter and getters

    public ChatMessage getNonNull(ChatMessage mes){
        if(this.text != null)mes.setText(this.text);
        if(this.translate != null)mes.setTranslate(this.translate);
        if(this.score != null)mes.setScore(this.score);
        if(this.selector != null)mes.setSelector(this.selector);
        if(this.extra != null)mes.setExtra(this.extra);
        if(this.bold != null)mes.setBold(this.bold);
        if(this.italic != null)mes.setItalic(this.italic);
        if(this.underlined != null)mes.setUnderlined(this.underlined);
        if(this.strikethrough != null)mes.setStrikethrough(this.strikethrough);
        if(this.obfuscated != null)mes.setObfuscated(this.obfuscated);
        if(this.color != null)mes.setColor(this.color);
        if(this.clickEvent != null)mes.setClickEvent(this.clickEvent);
        if(this.hoverEvent != null)mes.setHoverEvent(this.hoverEvent);
        if(this.insertion != null)mes.setInsertion(this.insertion);
        return mes;
    }
}

Now the problem is when Gson tries to parse this it of course runs into the problem that the second part of the "with" array is NOT a With object. 现在的问题是,当Gson试图解析它时,它当然会遇到“ with”数组的第二部分不是With对象的问题。 My problem is that I have no idea how to deal with this. 我的问题是我不知道该如何处理。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Edit1 What it is suppose to do: The with array is simply suppose to be a sort of "overwrite" as in any field from the main string can be overwritten and individually formatted inside. Edit1假定要执行的操作:with数组只是假定为一种“覆盖”,因为在主字符串的任何字段中都可以覆盖并且可以在内部单独格式化。 Thats what the null thing at the bottom of the With class is suppose to do, it is suppose to edit the main variables with their overwritten contents. 那就是With类底部的null事情应该做的事情,假设是用覆盖的内容来编辑主变量。 The unnamed field is suppose to be the text variable here. 此处未命名字段应该是文本变量。

Here's how you could write a custom deserializer for this: 这是您可以为此编写自定义反序列化器的方法:

class ChatMessageDezerializer implements JsonDeserializer<ChatMessage> {
    @Override
    public ChatMessage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        ChatMessage message = new ChatMessage();
        JsonObject obj = json.getAsJsonObject();
        message.translate = obj.get("translate").getAsString();
        JsonArray array = obj.getAsJsonArray("with");
        message.with.add(context.deserialize(array.get(0), With.class));
        message.with.add(array.get(1).getAsString());
        return message;
    }
}

and register it in your Gson parser: 并将其注册到您的Gson解析器中:

Gson gson = new GsonBuilder().registerTypeAdapter(ChatMessage.class, new ChatMessageDezerializer()).create();

Note that with is now a List<Object> since the most specific common type to the elements in the array are Object. 注意,由于数组中元素的最特定的通用类型是Object,所以with现在是List<Object> Also I just done the problematic part, the rest can be handled easily. 我也只是做了有问题的部分,其余的都可以很容易地处理。 Running this you end up with 运行它最终会导致

[With@b1a58a3, hi]

as the resulting list. 作为结果列表。 This assume you have a minimum control over the structure you get back (or at least you know in which format it would be). 假定您对返回的结构具有最小的控制(或者至少知道它的格式)。 It should give you a good starting point from there. 从那里应该为您提供一个良好的起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM