简体   繁体   English

JSON在Swift中编码非基本类型

[英]JSON encode non primitive types in Swift

Helo I would like to encode non standard types such as sims_float3x3 and [vector_float3] . Helo我想编码非标准类型,例如sims_float3x3[vector_float3] What is the recommended way to this? 推荐的方法是什么?

I tried to use Struct like so, 我试图像这样使用Struct

struct Example: Codable {
    var test_var1:simd_float3x3
    var test_var2:[vector_float3]
}

I get the error, does not conform to protocol 'Decodable' 我收到错误, does not conform to protocol 'Decodable'

I also tried, 我也尝试过

let data = try encoder.encode(test_var1)

I get the error - Argument type 'simd_float3x3' does not conform to expected type 'Encodable' 我收到错误- Argument type 'simd_float3x3' does not conform to expected type 'Encodable'

I currently can do like so, 我目前可以这样做,

let data_col1 = try encoder.encode(test_var1.columns.0) // simd_float3
let data_col2 = try encoder.encode(test_var1.columns.1) // simd_float3
let data_col3 = try encoder.encode(test_var1.columns.2) // simd_float3

But is there any way to do this more elegantly / efficiently? 但是,有什么方法可以更优雅/更有效地做到这一点吗?

You can use the same technique as shown in this answer for the outer array: 您可以对外部数组使用与此答案中所示相同的技术:

import SceneKit

extension simd_float3x3: Codable {
    public init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        try self.init(container.decode([float3].self))
    }
    public func encode(to encoder: Encoder) throws {
        var container = encoder.unkeyedContainer()
        try container.encode([columns.0, columns.1, columns.2])
     }
 }

Playground testing 游乐场测试

let simdFloat = simd_float3x3(float3(0, 1, 2), float3(3,4, 5), float3(6, 7, 8))
do {
    let data = try JSONEncoder().encode(simdFloat)
    let decodedObject = try JSONDecoder().decode(simd_float3x3.self, from: data)
    print(decodedObject)  // simd_float3x3([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])

} catch {
    print(error)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM