GSON:无知地将JSON转换为对象

时间:2016-10-07 11:57:55

标签: java gson android

我有成功的JSON模型

{
    data: {
        .....
    }
}

所以我创建了模型:

Class Model{
    public Data data;
}

我已经习惯了 new Gson().fromJson(Model.class)转换为Object。它工作正常。现在我的问题开始于我在相同的API中获得错误并且其json更改

{
    message: {
        .....
    }
}

我想在Json中使用相同的模型进行序列化。

Class Model{
    public Data data;
    public Massage message;
}

但它给了我以下例外:Expected a string but was BEGIN_OBJECT at line 1 column 13

1 个答案:

答案 0 :(得分:0)

只需配置并使用Jackson lib中的ObjectMapper

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.3</version>
</dependency>

映射器应定义为

ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

请参阅完整的演示示例

public class Demo {

    public static void main(String[] args) throws IOException {

        String jsonData = "{" +
                "    \"data\": {" +
                "    }" +
                "}";
        String jsonMessage = "{" +
                "    \"message\": {" +
                "    }" +
                "}";

        ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        Model modelData = mapper.readValue(jsonData, Model.class);
        Model modelMessage = mapper.readValue(jsonMessage, Model.class);


        System.out.println(modelData);
        System.out.println(modelMessage);


    }
}


class Model {

    private Data data;
    private Message message;

    @Override
    public String toString() {
        return "Model{" +
                "data=" + data +
                ", message=" + message +
                '}';
    }

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }

    public Message getMessage() {
        return message;
    }

    public void setMessage(Message message) {
        this.message = message;
    }

    private static class Data {}
    private static class Message {}
}

BTW,ObjectMapper是线程安全的,所以你可以定义一个常量,以便每次读取Json时都不创建它。

您可以在此处找到更多信息:http://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/ObjectMapper.html