json gson:将 null 视为空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9483348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:12:21  来源:igfitidea点击:

gson: Treat null as empty String

jsonparsinggson

提问by Adam Matan

I use google-gsonto serialize a Java map into a JSON string. It provides a builder handles null values:

我使用google-gson将 Java 映射序列化为 JSON 字符串。它提供了一个处理空值的构建器

Gson gson = new GsonBuilder().serializeNulls().create();

The problem is that the result is the string null, as in:

问题是结果是 string null,如下所示:

gson.toJson(categoriesMap));
{"111111111":null}

And the required result is:

所需的结果是:

{"111111111":""}

I can do a String-replace for nulland "", but this is ugly and prone to errors. Is there a native gson support for adding a custom String instead of null?

我可以对nulland进行字符串替换"",但这很丑陋并且容易出错。是否有本地 gson 支持添加自定义字符串而不是null

采纳答案by Jesse Wilson

If this were your application type, you could register a type adapter. But Gson doesn't allow you to change the serialized form of strings or primitive types.

如果这是您的应用程序类型,您可以注册一个类型适配器。但是 Gson 不允许您更改字符串或原始类型的序列化形式。

Your best bet is to change your Java objects. Or to loosen the restriction around nulls.

最好的办法是更改 Java 对象。或者放松对空值的限制。

回答by oznus

The above answer works okay for serialisation, but on deserialisation, if there is a field with null value, Gson will skip it and won't enter the deserialize method of the type adapter, therefore you need to register a TypeAdapterFactory and return type adapter in it.

上面的答案对于序列化是可行的,但是在反序列化时,如果有一个空值的字段,Gson 会跳过它并且不会进入类型适配器的反序列化方法,因此你需要注册一个 TypeAdapterFactory 并返回类型适配器它。

Gson gson = GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();


public static class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory {
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

        Class<T> rawType = (Class<T>) type.getRawType();
        if (rawType != String.class) {
            return null;
        }
        return (TypeAdapter<T>) new StringAdapter();
    }
}

public static class StringAdapter extends TypeAdapter<String> {
    public String read(JsonReader reader) throws IOException {
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return "";
        }
        return reader.nextString();
    }
    public void write(JsonWriter writer, String value) throws IOException {
        if (value == null) {
            writer.nullValue();
            return;
        }
        writer.value(value);
    }
}

回答by Alessio

In the actual version of gson you can do that:

在 gson 的实际版本中,您可以这样做:

    Object instance = c.getConstructor().newInstance();
    GsonBuilder gb = new GsonBuilder(); 
    gb.serializeNulls();
    Gson gson = gb.create(); 
    String stringJson = gson.toJson(instance);

回答by GeX

Answer from Google groups

来自Google 群组的回答

I had the same situation. This sample helped me.

我有同样的情况。这个样本帮助了我。

import java.lang.reflect.Type;

public class StringConverter implements JsonSerializer<String>, 
    JsonDeserializer<String> { 
public JsonElement serialize(String src, Type typeOfSrc, 
    JsonSerializationContext context) { 
    if ( src == null ) { 
        return new JsonPrimitive(""); 
    } else { 
        return new JsonPrimitive(src.toString());
    }
} 
public String deserialize(JsonElement json, Type typeOfT, 
    JsonDeserializationContext context) 
        throws JsonParseException { 
    return json.getAsJsonPrimitive().getAsString(); 
} 
}

And uses:

并使用:

GsonBuilder gb = new GsonBuilder(); 
gb.registerTypeAdapter(String.class, new StringConverter()); 
Gson gson = gb.create(); 

回答by Adam Matan

There's no solution. I've opened an issue at Gson's page; Hope it will get fixed on the next version.

没有解决办法。我在 Gson 的页面上打开了一个问题;希望下个版本能修复。

回答by Zoltán

I had almost the same problem that I could solve. I created an issuetoo.

我遇到了几乎相同的问题,我可以解决。我也创建了一个问题

I got this answer from lyubomyr-shaydariv:

我从lyubomyr-shaydariv得到了这个答案:

Gson does not touch missing values for, I guess, performance reasons and simplicitiy. You can easily implement a post-processing type adapter that would set the unaffected null-fields supposed to be optional to their default values

我猜,出于性能原因和简单性,Gson 不会触及缺失值。您可以轻松实现一个后处理类型适配器,该适配器将不受影响的空字段设置为它们的默认值是可选的

Based on the code snippet of the original answerI wrote a sample projectwith unit tests.

基于原始答案的代码片段,我编写了一个带有单元测试示例项目