【问题标题】:Converting Dictionary data to JSON format with Swift 5使用 Swift 5 将字典数据转换为 JSON 格式
【发布时间】:2020-12-02 04:14:32
【问题描述】:

在操场上,我使用以下代码将字典数据转换为 创建 JSON 文件。它有效,但并不完全符合我的要求。

var topLevel: [AnyObject] = []
var myDict : [String:Any] = [:]


myDict ["label"] = "label: carrots" as AnyObject
myDict ["coordinates"] =  [ "x: 120" as AnyObject,
                           "y: 164" as AnyObject,
                           "width: 230" as AnyObject,
                           "height: 119" as AnyObject]

let jsonData = try JSONSerialization.data(withJSONObject: myDict, options: .prettyPrinted)
let fileManager = FileManager.default
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let jsonUrl = url.appendingPathComponent("test.json")  

try? jsonData.write(to: jsonUrl )

当我们打开创建的 test.json 文件时,我们会看到。

 {
 "label" : "label: carrots",
"coordinates" : [
  "x: 120",
  "y: 164",
  "width: 230",
  "height: 119"
 ]
}

但我们想看到的是,坐标后面不是“{”,而是“[”。

          {
             "label": "carrots",
             "coordinates": {
             "x": 120
             "y": 164
             "width": 230
              "height": 119
            }

【问题讨论】:

  • 你写了myDict ["coordinates"] = something,但有些东西是数组,而不是字典,因此是 [] 而不是 {}""。另外,您希望"x": 120,"x": "120",而不是"x: 120", 在预期结果中: > let coordinates: [String: Any] = ["x": 120, "y": 164, "width": 230, "height": 119"]; myDict["coordinates] = coordinates 但您的预期结果不是有效的JSON,所以先澄清一下。

标签: ios json swift dictionary


【解决方案1】:

您可以使用以下内容:

myDict ["coordinates"] = [ "x" : 120,
                           "y" : 164,
                           "width" : 230,
                           "height": 119 ]

所以你在 Swift 中提供了一个带有键值对的字典。

如果你用上面的代码打印jsonData,你会得到:

"label" : "label: carrots",
"coordinates" : {
    "height" : 119,
    "y" : 164,
    "x" : 120,
    "width" : 230
}

JSONEncoder 替代方案

一般来说,您可能想看看 JSONEncoder 并改用它,请参阅此处的文档: https://developer.apple.com/documentation/foundation/jsonencoder

适用于 JSONEncoder 的示例如下所示:

struct TopLevel: Encodable {
    let label: String
    let coordinates: Coordinates
}

struct Coordinates: Encodable {
    let x: Int
    let y: Int
    let witdth: Int
    let height: Int
}

...


let topLevel = TopLevel(label: "carrots",
                        coordinates: Coordinates(x: 120,
                                                 y: 164,
                                                 witdth: 230,
                                                 height: 119))

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

if let data = try? encoder.encode(topLevel) {
    print(String(data: data, encoding: .utf8) ?? "")
}

优点是在编译时进行类型检查:编译器强制执行类型约束规则。

【讨论】:

    【解决方案2】:

    我听@Stephan Schlecht 并更改了这样的代码,它有效。 对于那些想知道我为什么要这样做的人;

    我将使用它需要的 Apple 的 Create ML 创建对象检测模型 此类数据为 JSON 以及图像。

    我能够通过使用图像分类器获得图片中对象图像的位置和尺寸。但是知道我打算使用更多的自动化来获取图片中的图像以生成此类数据。

    struct Coordinates: Codable {
      var x: Int
      var y: Int
      var width: Int
      var height: Int
    }
    
    
    struct ID: Codable {    
      var label: String = "carrot"
      var coordinates = Coordinates(x: 10, y: 10, width: 100, height: 100)
    }
    
    
    
    
    let  myData = ID()
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    let data = try encoder.encode(myData)
    print(String(data: data, encoding: .utf8)!)
    
    
    
    let fileManager = FileManager.default
    let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let jsonUrl = url.appendingPathComponent("test.json")  
    
    try? data.write(to: jsonUrl )
    
    {
      "label" : "carrot",
      "coordinates" : {
      "y" : 10,
      "x" : 10,
      "width" : 100,
      "height" : 100
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      相关资源
      最近更新 更多