我已经从javascript传递了一个字符串json对象到swift。
JS
'use strict';
var labdetail = function()
{
var labs = ["sdsdsd","suds","DH-sdsd","DH-sdsd"]
var labgrp = {labGrp:"R", labGrpDesc:"sdsd",labs:labs}
var labGroups = []
labGroups[0] = labgrp
var labs1 = ["dsdsd","suds","DH-sdsd","DH-dfdf]
var labgrp1 = {labGrp:"H", labGrpDesc:"dfdf",labs:labs}
labGroups[1] = labgrp1
return JSON.stringify(labGroups);
}
迅速
import UIKit
import JavaScriptCore
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let context = JSContext()
let returnLabResultJSPath = NSBundle.mainBundle().pathForResource("returnLabResult", ofType: "js")
let contentData = NSFileManager.defaultManager().contentsAtPath(returnLabResultJSPath!)
let content = NSString(data: contentData!, encoding: NSUTF8StringEncoding) as? String
// let returnresult = try String(contentsOfFile: returnLabResultJSPath!, encoding: NSUTF8StringEncoding)
context.evaluateScript(content)
let getlabfunction = context.objectForKeyedSubscript("labdetail")
var labresult = getlabfunction.callWithArguments([])
let labresultdict :dictionary = labresult.toDictionary()
print(labresult)
}
我想将其更改为原始结构。我尝试使用todictionary()
但是失败了
现在实验结果的结果是 [{" labGrp":" R"," labGrpDesc":"伤心难过","实验室":[& #34;伤心难过"," asdasd"," sadsad-sadsa"," DH-asdasd"]},{" labGrp&#34 ;:" H"" labGrpDesc":"生物学""实验室":[" asdsad"&# 34; asdsad""和"" DH-asdasd"]}]
我希望它是一个数组,数组[0]包含{" labGrp":" R"," labGrpDesc":"悲伤悲伤",#34;实验室":["伤心难过"," asdasd"," sadsad-sadsa"," DH -asdasd"]}
和数组[1]包含{" labGrp":" H"," labGrpDesc":"生物学","实验室":[" asdsad"" asdsad""和"" DH-asdasd"]}
答案 0 :(得分:0)
希望您需要反序列化JSon对象,然后它会生成Dictionary
对象。
例如:
var labresult = getlabfunction.callWithArguments([])
do{
if let data = labresult.dataUsingEncoding(NSUTF8StringEncoding) {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? [String:String]
}catch{ }