【问题标题】:Can I convert JSON file to kotlin multiplatform object in Swift?我可以在 Swift 中将 JSON 文件转换为 kotlin 多平台对象吗?
【发布时间】:2021-08-18 21:17:10
【问题描述】:

对于上下文:我正在使用 kotlin 多平台与我的两个应用程序的后端进行通信,我也在尝试遵循 Clean Architecture + MVVM。 我的多平台项目包含我的数据层(存储库和 dto),我的应用程序项目包含表示层和域层(VC、视图模型、用例)。

我正在尝试在多平台项目中模拟我的存储库。

我的 Kotlin 多平台项目中有一个类 (DTO),如下所示

@Serializable
data class LoginResponse(val data: LoginResponseBody){
    @Serializable
    data class LoginResponseBody(
        var accessToken: String,
        var lastChannel: String? = null,
        var lastDateTime: String? = null,
        var userId: String? = null,
        var transactionalKeyStatus: String? = null,
        var accessStatus: String? = null
    )
}

当我将该多平台项目添加到我的 xcode 项目中时,该对象将转换为:

__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("LoginResponse")))
@interface SharedEmaLoginResponse : SharedEmaBase
- (instancetype)initWithData:(SharedEmaLoginResponseLoginResponseBody *)data __attribute__((swift_name("init(data:)"))) __attribute__((objc_designated_initializer));
- (SharedEmaLoginResponseLoginResponseBody *)component1 __attribute__((swift_name("component1()")));
- (SharedEmaLoginResponse *)doCopyData:(SharedEmaLoginResponseLoginResponseBody *)data __attribute__((swift_name("doCopy(data:)")));
- (BOOL)isEqual:(id _Nullable)other __attribute__((swift_name("isEqual(_:)")));
- (NSUInteger)hash __attribute__((swift_name("hash()")));
- (NSString *)description __attribute__((swift_name("description()")));
@property (readonly) SharedEmaLoginResponseLoginResponseBody *data __attribute__((swift_name("data")));
@end;

我认为类 LoginResponse 会符合“Decodable”,但事实并非如此,这就是我的假存储库在我的 xcode 项目中的样子

final class LoginRepositoryTest : XCTestCase, IAuthRepository {
var hasError = false

func login(loginRequest: LoginRequest, success: @escaping (LoginResponse) -> Void, failure: @escaping (ErrorResponse) -> Void, completionHandler: @escaping (KotlinUnit?, Error?) -> Void) {
    if hasError {
        failure(ErrorResponse(messages: []))
    } else {
        let data = loadStub(name: "loginResponse", extension: "json")
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .secondsSince1970
        
        let loginData = try! decoder.decode(LoginResponse.self, from: data)
        success(loginData)
    }
}


func getKoin() -> Koin_coreKoin {}

}

错误

实例方法 'decode(_:from:)' 要求 'LoginResponse' 符合 'Decodable'

我想我有这两个选择:

  • 我使 kotlin 类符合“可解码”的要求
  • 我找到了一种无需使用 Decodable 即可将该 JSON 转换为该对象的方法

感谢任何帮助

【问题讨论】:

    标签: swift kotlin kotlin-multiplatform


    【解决方案1】:

    Kotlin 序列化并不意味着向类确认Decodable 协议。它旨在通过 kotlin 序列化从 kotlin 中使用,如下所示:

    val response: LoginResponse = Json.decodeFromString(
        LoginResponse.serializer(),
        string
    )
    

    附言最初你可以使用Json.decodeFromString<LoginResponse>(string),但据我所知,这在多平台上尚不支持

    网络和 JSON 解析是在 KMM 上最容易完成的事情,您也可以在那里编写测试,但如果您仍需要直接从 iOS 使用它,您可以尝试以下包装器:

    object JsonHelper {
        @Throws(Throwable::class)
        fun decodeRtcMsg(string: String) = 
            Json.decodeFromString(
                RtcMsg.serializer(), 
                string
            )
    }
    

    然后你就可以从 swift 中使用它了:

    do {
        try JsonHelper().decodeLoginResponse(string: "")
    } catch {
        print(error)
    }
    

    【讨论】:

      【解决方案2】:

      如果你真的需要 Decodable 我会创建一个 expect/actual 的 Decodable 为 ex:

      // in common
      expect interface Decodable
      
      // on Android
      actual interface Decodable
      
      // on iOS
      actual typealias Decodable = Decodable
      

      然后为您的 DTO 实现 Decodable。也许最好的例子是如何在共享代码中使用Parcelize:https://github.com/icerockdev/moko-parcelize/blob/master/parcelize/src/androidMain/kotlin/dev/icerock/moko/parcelize/Parcelize.kt

      【讨论】:

      • 我正在尝试复制它,但我在扩展中得到递归类型别名:iOS 上可解码
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2015-09-10
      • 1970-01-01
      相关资源
      最近更新 更多