简体   繁体   中英

Modifying .NET .asmx web service to return JSON instead of XML

I have created a simple.asmx web service in .NET as shown below:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Foo(string name)
{
    var customer = new {Name = name}; 

    JavaScriptSerializer json = new JavaScriptSerializer();
    return json.Serialize(customer); 
}

When I call this service it returns XML instead of JSON result. My iOS client has a dictionary which expects JSON format.

How can I make the .NET service to return JSON format instead of XML?

The dictionary never gets populated since.Net service returns XML instead of JSON.

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSLog(@"status code %d",request.responseStatusCode);

    if(request.responseStatusCode == 200) 
    {
        NSString *responseString = [request responseString];
        NSDictionary *responseDict = [responseString JSONValue];

        NSLog(@"%@",[responseDict objectForKey:@"name"]);    

    }

    NSLog(@"request finished");
}

I am also setting the content-type as shown below:

 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; 
    [request addRequestHeader: @"Content-Type" value: 
     @"application/json; charset=utf-8"]; 
    [request setPostValue:@"mama" forKey:@"name"];

    [request setDelegate:self]; 
    [request startAsynchronous]; 

The returned response I get is this:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{"Name":"mama"}</string>

I have strictly 0 knowledge of iOS and what would the correct syntax be but in order for an ASMX web service to return JSON you need to invoke it with HTTP POST verb and set the Content-Type request header to application/json (can't see from your code doing this). It will also preprend the result with the d property, for example:

{"d": { foo: 'bar' }}

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