Irrd Irrd - 1 month ago 6
iOS Question

How to convert string to NSArray in iOS

I have a

JSON
object and it has a key value pair like this

"AttachedDocument": "[{\"DocumentId\":354,\"DocumentName\":\"Screenshot_2016-04-15-00-35-11.png\",\"DocumentType\":\"image/png\"}]"


This value is coming as a string. How can I convert that into an
NSArray


FULL OBJECT

{
"LeaveEntryCode": 0,
"RequestId": 0,
"EmployeeCode": 17186,
"LeaveYear": 2016,
"LeaveTypeCode": 1,
"LeaveReasonCode": 0,
"BaseType": "ess",
"StartDate": "2016-10-24T00:00:00",
"EndDate": "2016-10-24T00:00:00",
"NoOfDays": 1,
"StartDateSession": "full",
"EndDateSession": "full",
"PreApproved": false,
"ForDate": "1901-01-01T00:00:00",
"Remarks": "test from Android",
"CoveringPersonCode": 0,
"AttachedDocument": "[{\"DocumentId\":354,\"DocumentName\":\"Screenshot_2016-04-15-00-35-11.png\",\"DocumentType\":\"image/png\"}]",
"RequestStatus": "P",
"Deleted": false,
"Status": false,
"CreatedBy": 0,
"CreatedDate": "0001-01-01T00:00:00",
"UpdatedBy": 0,
"UpdatedDate": "0001-01-01T00:00:00",
"DeletedBy": 0,
"DeletedDate": "0001-01-01T00:00:00",
"ModuleId": 2,
"ObjectId": 20,
"StartDateString": "10/24/2016",
"EndDateString": "10/24/2016",
"LeaveDayList": [
"10/24/2016-FH,10/24/2016-SH"
],
"SystemLeaveTypeCode": "ANN",
"LeaveTypeName": "ANNUAL",
"Employee": null,
"LieuDayList": null,
"BaseLeaveType": "ANN",
"CoveringPersonName": null,
"LeaveReasonName": "test",
"DocumentSource": "LEAVE"
}


This is the full
JSON
Object im getting. I am getting this via a web service.

Answer

Actually you are getting josn string as response, so you can convert it to josn object something like,

 NSString *yourString = @"[{\"DocumentId\":354,\"DocumentName\":\"Screenshot_2016-04-15-00-35-11.png\",\"DocumentType\":\"image/png\"}]";

NSError *error;
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                  options:NSJSONReadingMutableContainers 
                                    error:&error];

   NSLog(@"json object : %@",jsonObject);

here yourString means object for AttachedDocument key!