使用SwiftyJSON将NSDictionary转换为json字符串到json对象 [英] NSDictionary to json string to json object using SwiftyJSON

查看:512
本文介绍了使用SwiftyJSON将NSDictionary转换为json字符串到json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,我有一个字典数组,我需要它们作为json对象:

I have a use case where I have an array of dictionaries and I need them as a json object:

var data = [Dictionary<String, String>]()
//append items 
var bytes = NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions.allZeros, error: nil)
var jsonObj = JSON(NSString(data: bytes!, encoding: NSUTF8StringEncoding)!)

println(jsonObj)
println(jsonObj[0])

第一个打印声明给了我

[
    {"price":"1.20","city":"Foo","_id":"326105","street":"One"},
    {"price":"1.20","city":"Bar","_id":"326104","street":"Two"}
]

第二个

null

但我希望它能返回json数组中的第一个元素。我做错了什么?

but I would expect it to return the first element in the json array. What I am doing wrong?

推荐答案

根据文档,这应该是你所需要的。

According to the docs, this should be all you need.

var data = [Dictionary<String, String>]()
//append items 
var jsonObj = JSON(data)

println(jsonObj)
println(jsonObj[0])

将数组直接转换为 JSON 对象时遇到问题吗?

Are you having a problem with converting an array directly into a JSON object?

这篇关于使用SwiftyJSON将NSDictionary转换为json字符串到json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆