gpt4 book ai didi

json - 将 JSON 对象映射到 Swift 类/结构

转载 作者:IT王子 更新时间:2023-10-29 05:33:15 25 4
gpt4 key购买 nike

我需要“复制”从 JSON 中的远程 Web API 服务返回的条目。它看起来像这样:

{
"field1": "some_id",
"entity_name" = "Entity1"
"field2": "some name",
"details1": [{
"field1": 11,
"field2": "some value",
"data": {
"key1": "value1",
"key2": "value2",
"key3": "value3",
// any other, unknown at compile time keys
}
}],
"details2": {
"field1": 13,
"field2": "some value2"
}
}

这是我的尝试:

struct Entity1 {
struct Details1 {
let field1: UInt32
let field2: String
let data: [String: String]
}

struct Details2 {
let field1: UInt32
let field2: String
}

let field1: String
static let entityName = "Entity1"
let field2: String
let details1: [Details1]
let details2: Details2
}
  1. 为了这样的目标使用结构而不是类是个好主意吗作为我的?
  2. 我可以定义一个嵌套结构或类吗?Details1 并同时创建它的变量?

像这样:

//doesn't compile 
struct Entity1 {
let details1: [Details1 {
let field1: UInt32
let field2: String
let data: [String: String]
}]

最佳答案

您可以使用以下任何可用的开源库来处理 Swift 中 JSON 到 Object 的映射,看一看:

每个都有很好的初学者教程。

关于structclass的主题,你可以考虑以下来自The Swift Programming Language的文字文档:

Structure instances are always passed by value, and class instances are always passed by reference. This means that they are suited to different kinds of tasks. As you consider the data constructs and functionality that you need for a project, decide whether each data construct should be defined as a class or as a structure.

As a general guideline, consider creating a structure when one or more of these conditions apply:

  • The structure’s primary purpose is to encapsulate a few relatively simple data values.
  • It is reasonable to expect that the encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure.
  • Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.
  • The structure does not need to inherit properties or behavior from another existing type.

Examples of good candidates for structures include:

  • The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
  • A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.
  • A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.

In all other cases, define a class, and create instances of that class to be managed and passed by reference. In practice, this means that most custom data constructs should be classes, not structures.

希望对你有帮助

关于json - 将 JSON 对象映射到 Swift 类/结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29749652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com