简体   繁体   中英

Builiding JSON Response in String

I'm trying to build a JSON response to demo for an app. I've been able to build on in Java for Android but having trouble converting it to swift this is the Java Version:

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. 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 .

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]

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

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. An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.

  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

  • All dictionary keys are instances of NSString.

  • Numbers are not NaN or infinity.

This means, that you can create a JSON Object from a Dictionary like this:

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. 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. Except for debugging purposes, there should never be a string in sight.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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