简体   繁体   English

在字符串中构建JSON响应

[英]Builiding JSON Response in String

I'm trying to build a JSON response to demo for an app. 我正在尝试构建JSON响应以演示应用程序。 I've been able to build on in Java for Android but having trouble converting it to swift this is the Java Version: 我已经能够在Java for Android上构建,但是在将其转换为Swift时遇到麻烦,这是Java版本:

JSONObject response = new JSONObject("{'status': true, 'message':'success', 'data':[" +
                "{'id':'ITM10001', 'area':'Regional', 'aboveRegion':'West', 'aboveScore':'7/10', 'belowRegion':'Lagos', 'belowScore':'4/10'}," +
                "{'id':'ITM10002', 'area':'Area', 'aboveRegion':'V/Island', 'aboveScore':'8/10', 'belowRegion':'Ogba', 'belowScore':'3/10'}, " +
                "{'id':'ITM10003', 'area':'Owned Restaurants', 'aboveRegion':'Yaba', 'aboveScore':'9/10', 'belowRegion':'Sabo', 'belowScore':'2/10'}, " +
                "{'id':'ITM10004', 'area':'Franchised Restaurants', 'aboveRegion':'Idumota', 'aboveScore':'9/10', 'belowRegion':'Itafaji', 'belowScore':'3/10'}, " +
                "{'id':'ITM10005', 'area':'Owned Restaurants', 'aboveRegion':'Mushin', 'aboveScore':'10/10', 'belowRegion':'Layi', 'belowScore':'2/10'}] }");

And this is what I did in swift using a code I saw online here JSONURL but still printing error out. 这就是我使用在JSONURL上在线看到的代码迅速完成的工作,但仍然打印出错误。 Any help would be appreciated 任何帮助,将不胜感激

 let json = JSON.parse("{\"status\": true, \"message':\"success\", \"data\":[" +
        "{\"status\": \"Approved\", \"paidDate\": \"Paid on 15 Aug 2015\", \"statusDate\": \"30 June 2015\", \"statusPrice\": \"5000\"}," +
        "{\"status\": \"Rejected\", \"paidDate\": \"Paid on 15 Jun 2015\", \"statusDate\": \"30 May 2015\", \"statusPrice\": \"7000\"}," +
        "{\"status\": \"Approved\", \"paidDate\": \"Paid on 15 July 2015\", \"statusDate\": \"30 June 2015\", \"statusPrice\": \"9000\"}," +
        "{\"status\": \"Rejected\", \"paidDate\": \"Paid on 15 May 2015\", \"statusDate\": \"30 April 2015\", \"statusPrice\": \"8000\"} ]}")

You don't need a third-party library for that, you can use NSJSONSerialization . 为此,您不需要第三方库,可以使用NSJSONSerialization

Also, be careful that all your quotes are double quotes and are escaped (there was a single quote somewhere in your example where it should have been a double quote). 另外,请注意,所有引号都是双引号,并且会被转义(示例中某处有一个单引号,应该将双引号括起来)。

let str = "{\"status\": true, \"message\":\"success\", \"data\":[" + "{\"status\": \"Approved\", \"paidDate\": \"Paid on 15 Aug 2015\", \"statusDate\": \"30 June 2015\", \"statusPrice\": \"5000\"}," + "{\"status\": \"Rejected\", \"paidDate\": \"Paid on 15 Jun 2015\", \"statusDate\": \"30 May 2015\", \"statusPrice\": \"7000\"}," + "{\"status\": \"Approved\", \"paidDate\": \"Paid on 15 July 2015\", \"statusDate\": \"30 June 2015\", \"statusPrice\": \"9000\"}," + "{\"status\": \"Rejected\", \"paidDate\": \"Paid on 15 May 2015\", \"statusDate\": \"30 April 2015\", \"statusPrice\": \"8000\"}]}"

if let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false),
    let jsonDict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [String:AnyObject] {
    println(jsonDict)
}

Result: 结果:

[status: 1, data: ( { paidDate = "Paid on 15 Aug 2015"; status = Approved; statusDate = "30 June 2015"; statusPrice = 5000; }, { paidDate = "Paid on 15 Jun 2015"; status = Rejected; statusDate = "30 May 2015"; statusPrice = 7000; }, { paidDate = "Paid on 15 July 2015"; status = Approved; statusDate = "30 June 2015"; statusPrice = 9000; }, { paidDate = "Paid on 15 May 2015"; status = Rejected; statusDate = "30 April 2015"; statusPrice = 8000; } ), message: success] [状态:1,数据:( {{paidDate =“ Pay on 15 Aug 2015”; status = Approved; statusDate =“ 2015年6月30日”; statusPrice = 5000;},{paidDate =“ Paid on 15 Jun 2015”; status =已拒绝; statusDate =“ 2015年5月30日”; statusPrice = 7000;},{paidDate =“ 2015年7月15日支付”; status =批准; statusDate =“ 2015年6月30日”; statusPrice = 9000;},{paidDate =“支付在2015年5月15日”;状态=已拒绝;状态日期=“ 2015年4月30日”;状态价格= 8000;},消息:成功]

UPDATE: 更新:

Check for error if you can't convert a specific string: 如果无法转换特定字符串,请检查错误:

var error:NSError?
if let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false),
    let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? [String:AnyObject] {
        if error == nil {
            println(json)
        } else {
            println(error)
        }
}

Update for Swift 2.0 Swift 2.0更新

do {
    if let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false),
        let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject] {
            print(json)
    }
} catch let error as NSError {
    print(error)
}

From the official Apple Documentation: 从苹果官方文档中:

You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON. 您可以使用NSJSONSerialization类将JSON转换为Foundation对象,并将Foundation对象转换为JSON。 An object that may be converted to JSON must have the following properties: 可能转换为JSON的对象必须具有以下属性:

  • The top level object is an NSArray or NSDictionary. 顶级对象是NSArray或NSDictionary。

  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull. 所有对象都是NSString,NSNumber,NSArray,NSDictionary或NSNull的实例。

  • All dictionary keys are instances of NSString. 所有字典键都是NSString的实例。

  • Numbers are not NaN or infinity. 数字不是NaN或无穷大。

This means, that you can create a JSON Object from a Dictionary like this: 这意味着,您可以像这样从Dictionary创建JSON对象

let dict = ["fruit": "orange", "chesse": "brie", "cars": ["bmw", "mercedes", "fiat"]]
if let data = NSJSONSerialization.dataWithJSONObject(dict, options: nil, error: nil)
{
   let stringFromData = NSString(data: data, encoding: NSStringEncoding.allZeros)

   println(stringFromData!) 
  // prints: "{"fruit":"orange","chesse":"brie","cars":["bmw","mercedes","fiat"]}"
}

You should never, ever build JSON responses as strings. 您永远都不应将JSON响应构建为字符串。 It's guaranteed to break sooner or later. 保证早晚打破。

You should build JSON responses as dictionaries or arrays, as appropriate, then convert to NSData using NSJSONSerialization. 您应该根据需要将JSON响应构建为字典或数组,然后使用NSJSONSerialization转换为NSData。 Except for debugging purposes, there should never be a string in sight. 除了用于调试目的,永远不会出现字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM