NSJSONSerialization 与 C# Rest 服务
Posted
技术标签:
【中文标题】NSJSONSerialization 与 C# Rest 服务【英文标题】:NSJSONSerialization with C# Rest Service 【发布时间】:2012-07-13 19:44:07 【问题描述】:所以我完全是 C# 和网络方面的菜鸟,并试图弄清楚一些事情。有一些代码是这样说的:
[WebInvoke(UriTemplate = "People", Method = "GET", ResponseFormat = WebMessageFormat.Json)]
public string GetPeople()
Person results = DataAccess.ParsePeople();
System.WebScrip.Serialization.javascriptSerializer oSerializer = oSerializer.MaxJsonLength = int.MaxValue;
string sJSON = oSerializer.Serialize(results);
return sJSON;
当我输入此方法的 url 时,我的响应如下:
"\"AddressesCollection\":[\"Street\":\"1234 Temp Dr\",\"Zip\":94011,\"Street\":\"56789 Nothing Dr\",\"Zip\":2222,\"ErrorMessage\":\"SUCCESS\""
我试图在 iPad 端学习本教程:http://www.raywenderlich.com/5492/working-with-json-in-ios-5
查看他们用作示例的网站,JSON 输出如下所示:
"paging":"page":1,"total":4440,"page_size":20,"pages":222,"loans":["id":447290,"name": "Rosa","description":"languages":["es","en"],"status":"fundraising","funded_amount":0,"basket_amount":0,"image":" id":1134583,"template_id":1,"activity":"Animal Sales","sector":"Agriculture","use":"购买稗鸡和饲料。","location":"country_code ":"PE","country":"Peru","town":"M\u00f3rrope - Lambayeque","geo":"level":"country","pairs":"-10 -76", "type":"point","partner_id":143,"posted_date":"2012-07-13T19:00:05Z","planned_expiration_date":"2012-08-12T19:00:05Z","loan_amount ":400,"borrower_count":1,"id":447292,"na
在 iPad 上,当我这样做时:
NSDictionary *fields = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
或
NSArray *fields = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
两者都是空的。是不是正确的 JSON 的 C# 输出?谢谢。
【问题讨论】:
您的 Json 字符串(以AddressesCollection
开头)无效
@L.B 是因为 JavaScriptSerializer 吗?
【参考方案1】:
您的 JSON 字符串在某处缺少结束 ]
。
假设您发布的字符串正是服务器返回的内容,您可能还需要删除反斜杠以使其成为有效的 JSON。
NSString *responseString = [[[NSString alloc] initWithData:response] stringByReplacingOccurrencesOfString:@"\\" withString:@""];
NSDictionary *fields = [NSJSONSerialization JSONObjectWithData:responseString options:kNilOptions error:&error];
【讨论】:
您是否碰巧知道 C# 代码是否导致输出看起来像每个字符串对象周围都有反斜杠?谢谢。 是的。有关更多信息以及潜在的解决方案,请参阅 this reference。以上是关于NSJSONSerialization 与 C# Rest 服务的主要内容,如果未能解决你的问题,请参考以下文章
NSDictionary 到 JSON 与 NSJSONSerialization 问题
NSJSONSerialization 不解析这个 JSON