如何编写JSON混合模式数据?

时间:2015-05-11 18:35:48

标签: json swift nsjsonserialization

我想写一个字典和数据数组的组合。

我的数据看起来像这样

我使用的功能是

  func writeJSONdata()
  {
    var error: NSError?
    var filename:String = "testWrite.json"
    var dict:NSMutableDictionary = ["3Dmodel":"Model_Student_v3",
"3Ddata":"testdata file",
"3DColors":"color file name"]

    var myArray:[Float] = [1.0,-0.13131,12.0]

    let dirPaths = NSSearchPathForDirectoriesInDomains(
      NSSearchPathDirectory.DocumentDirectory,
      NSSearchPathDomainMask.UserDomainMask,
      true
    )
    let docsDir = dirPaths[0] as String
    let filePath = docsDir.stringByAppendingPathComponent(filename)

    if let outputJSON = NSOutputStream(toFileAtPath: filePath, append: false)
    {
      outputJSON.open()
      NSJSONSerialization.writeJSONObject(dict, toStream: outputJSON, options: NSJSONWritingOptions(), error: &error)
      NSJSONSerialization.writeJSONObject(myArray, toStream: outputJSON, options: NSJSONWritingOptions(), error: &error)
      outputJSON.close()
    }
  }

当然JSON无效,因为没有附加到数组的名称。

> {
>     "3Dmodel": "Model_Student_v3",
>     "3DColors": "color file name",
>     "3Ddata": "testdata file" }[
>     1,
>     -0.13131,
>     12 ]

应该看起来像

{
    "3Dmodel": "Model_Student_v3",
    "3DColors": "color file name",
    "3Ddata": "testdata file",
    "data": [
        1,
        -0.13131,
        12
    ]
}

1 个答案:

答案 0 :(得分:1)

只需使用dict [" data"] = myArray然后写dict。