2

I created a RESTful api in Visual Studio with the following Controller:

[RoutePrefix("api/json")]
    public class JsonController : ApiController
    {
        [Route("person")]
        public string GetPerson()
        {
            Person person = new Person(0, "John Doe", 99);

            JavaScriptSerializer serialize = new JavaScriptSerializer();
            return serialize.Serialize(person);
        }
    }

When I navigate to the api through the browser I get this result:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">{"Id":0,"Name":"John Doe","Age":99}</string>

In my Swift code I´m trying to get this result and parse it to my textboxes with the following code:

 var url = "THE URL TO MY SITE"
        var request : NSMutableURLRequest = NSMutableURLRequest()
        request.URL = NSURL(string: url)
        request.HTTPMethod = "GET"

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
            let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

            if (jsonResult != nil) {
                println(jsonResult)
                // process jsonResult
                //self.txtStringiFiedText.text = jsonResult["Name"] as NSString
            } else {
                println(error)
            }
        })

When I´m running this I get this error: 0x0000000000000000

But when I for example test this API: http://jsonplaceholder.typicode.com/posts/1 it works and I get the data provided in the JSON.

So there has to be something wrong with my RESTful API Controller method. Anyone has an idea of what it could be?

Appreciate help.

  • 1
    Rather than returning JSON, your API is returning a string that has been serialized as XML. You need to 1) Just return a `Person` -- it get serialized for you. 2) Make sure a JSON formatter is configured: http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization. 3) Configure the "Accept" header of your request to accept JSON. Not sure how to do this on swift, maybe see here: https://stackoverflow.com/questions/4456966/how-to-send-json-data-in-the-http-request-using-nsurlrequest – dbc Apr 04 '15 at 16:24
  • @dbc all I did was to return the person instead and it worked, thanks a lot! –  Apr 04 '15 at 17:07

1 Answers1

0

Rather than returning JSON, your API is returning a string that has been serialized as XML. You need to

  1. Just return a Person -- it get serialized for you.
  2. Make sure a JSON formatter is configured: http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization. (It should be by default.)
dbc
  • 104,963
  • 20
  • 228
  • 340