如何使用数组从Dictionary创建JSON

时间:2016-04-22 17:17:12

标签: json swift

我有一个对象" itensList",它有字段" name"," createdAt"以及一系列" itens"。

我希望能够构建如下所示的JSON:

getCapacity()

我尝试过几种不同的方法但没有成功。

物品对象

 {
  "name": "List name"
  "CreatedAt": "12:12 12/12/2016"
  "itens": [
    {
      "title": "Item title"
      "CreatedAt": "12:13 12/12/2016"
      "isDone": false
    },
    {
      "title": "Another item title"
      "CreatedAt": "12:14 12/12/2016"
      "isDone": true
    }
   ]
 }

物品清单对象

class Item: Object {

    dynamic var name = ""
    dynamic var createdAt = NSDate()
    dynamic var isDone = false

}

3 个答案:

答案 0 :(得分:1)

对于这个例子,让我们创建一个类似于你必须具有的对象:

class Iten {
    let title:String
    let createdAt:String
    let isDone:Bool

    init(title: String, createdAt: String, isDone: Bool) {
        self.title = title
        self.createdAt = createdAt
        self.isDone = isDone
    }

}

我建议的技巧是添加一个将返回字典的计算值:

class Iten {
    let title:String
    let createdAt:String
    let isDone:Bool

    init(title: String, createdAt: String, isDone: Bool) {
        self.title = title
        self.createdAt = createdAt
        self.isDone = isDone
    }

    var toDictionary: [String:AnyObject] {
        return ["title": title, "createdAt": createdAt, "isDone": isDone]
    }
}

让我们用它:

let iten1Dict = Iten(title: "title1", createdAt: "date1", isDone: false).toDictionary
let iten2Dict = Iten(title: "title2", createdAt: "date2", isDone: true).toDictionary

我们现在制作封装字典:

let dict: [String:AnyObject] = ["name": "List name", "createdAt": "dateX", "itens": [iten1Dict, iten2Dict]]

要完成,我们将此字典编码为JSON data ,然后我们将其解码为字符串:

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted)
    if let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding) {
        print(jsonString)
    }
} catch let error as NSError {
    print(error)
}

瞧瞧:

{
  "createdAt" : "dateX",
  "itens" : [
    {
      "title" : "title1",
      "createdAt" : "date1",
      "isDone" : false
    },
    {
      "title" : "title2",
      "createdAt" : "date2",
      "isDone" : true
    }
  ],
  "name" : "List name"
}

答案 1 :(得分:0)

像这样:

-(void)startPlaybackForItemWithURL:(NSURL*)url {

     // First create an AVPlayerItem
     AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:url];

     // Subscribe to the AVPlayerItem's DidPlayToEndTime notification.


    [[NSNotificationCenter defaultCenter] 
      addObserver:self 
        selector:@selector(itemDidFinishPlaying:) 
        name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];

    // Begin playback
    [player play]
} 

-(void)itemDidFinishPlaying:(NSNotification *) notification {
     // Will be called when AVPlayer finishes playing playerItem
     [self dismissViewControllerAnimated:YES completion:Nil]
     [[NSNotificationCenter defaultCenter] 
        removeObserver:self 
        name:AVPlayerItemDidPlayToEndTimeNotification 
        object:Nil];

}

只需将var item = [ "title": "Item title", "CreatedAt": "12:13 12/12/2016", "isDone": false ] var mainDictionary = [ "name": "List name", "CreatedAt": "12:12 12/12/2016", "items": [item] ] 转换为json,就像这样:

NSJSONSerialization

<强>更新

如果需要在字典中向数组添加值,可以这样做:

do {
    let json = try NSJSONSerialization.dataWithJSONObject(mainDictionary, options: [])
} catch {
    print(error)
}

答案 2 :(得分:0)

圣拉斐尔,

这段代码构建了一个JSON查询。它应该让你开始,只是继续黑客攻击,你会找到一种方法!这就是编程的乐趣!

func JSONquery() 
 let request = NSMutableURLRequest(URL: NSURL(string:        "https://api.dropboxapi.com/2/files/get_metadata")!)
    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    request.addValue("application/json",forHTTPHeaderField: "Content-Type")
    request.addValue("path", forHTTPHeaderField: lePath)
    let cursor:NSDictionary? = ["path":lePath]
    do {
        let jsonData = try NSJSONSerialization.dataWithJSONObject(cursor!, options: [])
        request.HTTPBody = jsonData
        print("json ",jsonData)
    } catch {
        print("snafoo alert")
    }

        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        if let error = error {
            completion(string: nil, error: error)
            return
        }
        let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
        //print("Body: \(strData)\n\n")
        do {
            let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers);
            self.jsonPParser(jsonResult,field2file: "ignore")
            /*for (key, value) in self.parsedJson {
                print("key2 \(key) value2 \(value)")
            }*/

            completion(string: "", error: nil)
        } catch {
            completion(string: nil, error: error)
        }
    })
    task.resume()

}