Aje*_*eet 21 json objective-c nsmutablearray nsarray ios
我正在为现有网站创建一个应用程序.它们目前具有以下格式的JSON:
[
{
"id": "value",
"array": "[{\"id\" : \"value\"} , {\"id\" : \"value\"}]"
},
{
"id": "value",
"array": "[{\"id\" : \"value\"},{\"id\" : \"value\"}]"
}
]
Run Code Online (Sandbox Code Playgroud)
它们在使用Javascript转义\字符后解析.
我的问题是当我使用以下命令在iOS中解析它时:
NSArray *result = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&localError];
Run Code Online (Sandbox Code Playgroud)
这样做:
NSArray *Array = [result valueForKey:@"array"];
Run Code Online (Sandbox Code Playgroud)
而不是Array我得到的NSMutableString对象.
该网站已经投入生产,因此我无法要求他们更改现有结构以返回正确的JSON对象.对他们来说这将是很多工作.
所以,直到他们改变底层stucture,有没有什么办法可以让它工作在iOS像他们做与javascript他们website?
任何帮助/建议对我都非常有帮助.
Rob*_*Rob 42
正确的JSON应该看起来像:
[
{
"id": "value",
"array": [{"id": "value"},{"id": "value"}]
},
{
"id": "value",
"array": [{"id": "value"},{"id": "value"}]
}
]
Run Code Online (Sandbox Code Playgroud)
但是,如果您坚持使用问题中提供的格式,则需要使字典变为可变,NSJSONReadingMutableContainers然后NSJSONSerialization再为每个字典调用array条目:
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (error)
NSLog(@"JSONObjectWithData error: %@", error);
for (NSMutableDictionary *dictionary in array)
{
NSString *arrayString = dictionary[@"array"];
if (arrayString)
{
NSData *data = [arrayString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
dictionary[@"array"] = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error)
NSLog(@"JSONObjectWithData for array error: %@", error);
}
}
Run Code Online (Sandbox Code Playgroud)
Raj*_*han 13
试试这个简单的方法......
- (void)simpleJsonParsing
{
//-- Make URL request with server
NSHTTPURLResponse *response = nil;
NSString *jsonUrlString = [NSString stringWithFormat:@"http://domain/url_link"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Get request and response though URL
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//-- JSON Parsing
NSMutableArray *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(@"Result = %@",result);
for (NSMutableDictionary *dic in result)
{
NSString *string = dic[@"array"];
if (string)
{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
dic[@"array"] = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
}
else
{
NSLog(@"Error in url response");
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83117 次 |
| 最近记录: |