java - 使用 Gson 在 Java 中反序列化任意 JSON 并尊重整数

标签 java json gson

我有一些 JSON 字符串片段,可能如下所示:

{label: "My Label"}

{maxlength: 5}

{contact: {name: "John", "age": 5, children: [{"name": "Mary"]}}

等等,即它可以是具有任何键名称或值类型的任何 JSON 对象。

现在我正在反序列化做一些非常简单的事情,如下所示:

final Gson gson = new Gson();
Object newValue = gson.fromJson(stringValue, Object.class);

这适用于 99% 的用例。但是as is mentioned here ,它将任何整数转换为 double 。

我可以按照其他地方推荐的方式注册类型适配器。所以我写了以下内容:

final Gson gson = new GsonBuilder()
                        .registerTypeAdapter(Object.class, new DoubleToInt())
                        .create();
Object newValue = gson.fromJson(stringValue, Object.class);

private static class DoubleToInt implements JsonDeserializer<Object>{

    @Override  
    public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

        // do my custom stuff here

        return json;
    }
}

但这根本不起作用。这就像类型适配器甚至没有注册,因为断点甚至从未在 deserialize 中命中。方法。

最佳答案

正如您链接的帖子所建议的,您应该创建自定义类,所以我这样做了并且它工作正常:

public class Test {
    public static void main(String[] args) {
        final Gson gson = new GsonBuilder()
            .registerTypeAdapter(MyClass.class, new DoubleToInt())
            .create();
        String stringValue = "{contact: {name: \"John\", \"age\": 5, children: [{\"name\": \"Mary\"}]}}";

        MyClass newValue = gson.fromJson(stringValue, MyClass.class);
        System.out.println(newValue.toString());
    }

    private static class DoubleToInt implements JsonDeserializer<MyClass> {

        @Override
        public MyClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

            // do my custom stuff here

            return new MyClass(json);
        }
    }
}

class MyClass {
    private JsonElement element;

    MyClass(JsonElement element) {
        this.element = element;
    }

    @Override
    public String toString() {
        return element.toString();
    }
}

关于java - 使用 Gson 在 Java 中反序列化任意 JSON 并尊重整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53674447/

相关文章:

java - 从多层ObjectNode中检索线结构

java - 从 Url java 读取 JSON

java - Java、Scala、Groovy 和 jRuby 的平台将用什么语言实现?

java - Classname.Variable 使用 Classname 作为变量

java - 如何在Spring中自定义SpEL解析器?

json - 将 JSON 数据从应用程序组件传递到 Angular 6 中的另一个组件

json - 使用Gson从JSON字符串转换为数据类对象列表?

java - 如何从firebase实时数据库获取数据

c# - Json数据列表、数组

php - 使用Services PHP/Mysql Xamarin登录失败