Moshi/Kotlin-如何将NULL JSON字符串序列化为空字符串? [英] Moshi/Kotlin - How to serialize NULL JSON strings into empty strings instead?

查看:868
本文介绍了Moshi/Kotlin-如何将NULL JSON字符串序列化为空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个空安全的String适配器,它将将此JSON {"nullString": null}序列化为:Model(nullString = ""),以便将任何我希望是String的具有'null'值的JSON替换为""(假设存在这样的数据类:data class Model(val nullString: String))

I'm trying to write a null-safe String adapter that will serialize this JSON {"nullString": null} into this: Model(nullString = "") so that any JSON with a 'null' value that I expect to be a String will be replaced with "" (assuming there exists a data class like this: data class Model(val nullString: String))

我编写了一个自定义适配器来尝试处理此问题:

I wrote a custom adapter to try and handle this:

class NullStringAdapter: JsonAdapter<String>() {
    @FromJson
    override fun fromJson(reader: JsonReader?): String {
        if (reader == null) {
            return ""
        }

        return if (reader.peek() == NULL) "" else reader.nextString()
    }

    @ToJson
    override fun toJson(writer: JsonWriter?, value: String?) {
        writer?.value(value)
    }
}

...试图解决此解析错误:

...in an attempt to solve this parsing error:

com.squareup.moshi.JsonDataException: Expected a name but was NULL at path $.nullString

Moshi解析代码:

Moshi parsing code:

val json = "{\"nullString\": null}"

val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .add(NullStringAdapter())
    .build()

val result = moshi.adapter(Model::class.java).fromJson(configStr)

我在这里想念什么?还是moshi的新手,因此感谢您的帮助!

What am I missing here? Still new to moshi so any help is appreciated!

推荐答案

直接的问题是缺少消耗空值的reader.nextNull()调用.

The immediate problem is the missing reader.nextNull() call to consume the null value.

您还可以在此处执行其他几项清理操作. 对于@FromJson,不需要实现JsonAdapter. 另外,JsonReader和JsonWriter不能为空.

There are a couple other cleanup things you can do here, too. With @FromJson, implementing JsonAdapter is unnecessary. Also, the JsonReader and JsonWriter are not nullable.

object NULL_TO_EMPTY_STRING_ADAPTER {
  @FromJson fun fromJson(reader: JsonReader): String {
    if (reader.peek() != JsonReader.Token.NULL) {
      return reader.nextString()
    }
    reader.nextNull<Unit>()
    return ""
  }
}

并使用添加适配器:

val moshi = Moshi.Builder()
    .add(NULL_TO_EMPTY_STRING_ADAPTER)
    .add(KotlinJsonAdapterFactory())
    .build()

这篇关于Moshi/Kotlin-如何将NULL JSON字符串序列化为空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆