如何写入JSON混合模式数据?
How to write JSON mixed mode data?
我想写一个字典和数据数组的组合。
我的数据是这样的
我使用的函数是
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
]
}
就用dict ["data"] = myArray 然后写dict。
我想写一个字典和数据数组的组合。
我的数据是这样的
我使用的函数是
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
]
}
就用dict ["data"] = myArray 然后写dict。