简体   繁体   English

使用 Swift 5 将字典数据转换为 JSON 格式

[英]Converting Dictionary data to JSON format with Swift 5

At play ground I used following code to convert dictionary data to create JSON file.在操场上,我使用以下代码转换字典数据以创建 JSON 文件。 It worked but not exactly as I wanted.它有效,但不完全符合我的要求。

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 )

When we open created test.json file we see that.当我们打开创建的 test.json 文件时,我们会看到。

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

But we want to see is that, instead of "{" we are getting "[" after coordinates.但我们想看到的是,坐标后得到的不是“{”,而是“[”。

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

You could use the following:您可以使用以下内容:

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

So you are supplying a dictionary with key value pairs in Swift.因此,您在 Swift 中提供了一个包含键值对的字典。

If you print the jsonData with the above code, you will get:如果你用上面的代码打印 jsonData,你会得到:

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

JSONEncoder Alternative JSONEncoder 替代方案

In general you might want to take a look at JSONEncoder and use it instead, see the documentation here: https://developer.apple.com/documentation/foundation/jsonencoder一般来说,您可能想看看 JSONEncoder 并改用它,请参阅此处的文档: https://developer.apple.com/documentation/foundation/jsonencoder

Your example adapted for use with JSONEncoder would look something like this:您适用于 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) ?? "")
}

The advantage is type checking during compile time: the compiler enforces type constraint rules.优点是在编译时进行类型检查:编译器强制执行类型约束规则。

I listen @Stephan Schlecht and changed code like this it worked.我听@Stephan Schlecht 并更改了这样的代码,它起作用了。 And for the people who wonder why I am trying to do this;对于那些想知道我为什么要这样做的人;

I will create object detection model with Apple's Create ML it needs this kind data as JSON along with the images.我将使用 Apple 的 Create ML 创建 object 检测 model 它需要此类数据作为 JSON 以及图像。

I was able to get positions and dimensions of the objects images in pictures by using Image Classifier.通过使用图像分类器,我能够获得图片中对象图像的位置和尺寸。 But know I am planing to use more automation to get images in pictures to produce this type of data.但是知道我计划使用更多的自动化来获取图片中的图像以生成此类数据。

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
  }
}

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

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