Android Studio 拒绝承认继承层次结构

标签 android json inheritance kotlin

这与实现'org.json:json:20180813'

所以我有一个 User 类,它允许将自身转换为 json 字符串以进行持久化:

data class User(override val name:String, override val creds:ICredentials) : IUser, isEncodable<IUser>{
    override val isLoggedIn by lazy { creds is Credentials.Valid }

    override fun encode():String{
        val credsEncoding = creds.encode()

        return JSONStringer().withObject { it
                .key("type").value(this::class.java.name)
                .key("name").value(name)
                .key("creds").value(credsEncoding)
        }.toString()
    }
}

其中 withObject 是一个扩展函数:

fun JSONWriter.withObject(content:(JSONWriter)->JSONWriter) = content(`object`() as JSONWriter).endObject()

这似乎可以正常编译和工作。

但是,AndroidStudio 将其标记为红色并声明

Unresolved reference

None of the following candidates is applicable because of receiver type mismatch

public fun JSONWriter.withObject(content:(JSONWriter)->JSONWriter):JSONWriter! defined in [...]`

如果我试图“作弊”并将其写成

(JSONStringer() as JSONWriter).withObject { it
    ...
}

错误变成警告

This cast can never succeed.

但显然,它确实如此。

这是为什么呢?我该如何摆脱这个“错误”?

最佳答案

This is with implementation 'org.json:json:20180813'

这不太可能奏效。

Why is that?

在过去的 11 年里,Android 在 Android SDK 中有一个 org.json 类的副本。 This includes JSONStringer .你不能有两个具有相同完全限定名称的类,固件总是获胜。您的冲突类的副本将不会被使用,而是使用固件。在过去的 11 年里,固件的 API 没有太大变化。

And how do I get rid of this "error"?

删除实现'org.json:json:20180813'。要么:

  • 使用 Android SDK 的内置 org.json 类,或者
  • 使用 Android SDK 的 JsonReaderJsonWriter 类,或者
  • 使用不同的 JSON 解析器(例如 Gson、Jackson、Moshi)

关于Android Studio 拒绝承认继承层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54383296/

相关文章:

java - 通过 OSMDroid 使用在线存储中的 MBTiles

python - 多个 json 转 csv

c++ - 在 C++ 中为派生类定义问题

java - 如何引用泛型参数自身的参数,比如T2<T>中的T?

java - 从父类对象调用子类方法

未找到 Android sdkmanager。更新到最新的 Android SDK 并确保已安装 cmdline-tools 以解决此问题

Android 2.2 + SQLite + 定义参照完整性约束

json - jinja2.exceptions.TemplateRuntimeError : no filter named 'split' 错误

c# - WCF 应答处理 C#

java - map View : Could not find class A referenced from method B