Saturday, February 17, 2018

-[__NSSingleObjectArrayI dataUsingEncoding:] Objective C

Few days back, I was trying to parse a JSON string which I was getting from the server. Parsing 
JSON string is very easy to do. You just need to convert the JSON string into a NSData. Then serialize this data, then you will get the array or dictionary of that JSON string.

But this easy procedure becomes so much irritating when I was getting this -[__NSSingleObjectArrayI dataUsingEncoding:] NSException while I was trying to convert the JSON string to NSData. After spending an hour I realized my string was in two first brackets. That means I was providing an array to the conversation procedure of JSON String to NSData. That is the reason I was getting the mentioned exception. I am describing my situation below.

Image 1: Getting this array of dictionary from server.

Look at the image 1. Now I need to parse the JSON. Two things to focus here. The first one is the JSON ( here "List") is in a dictionary and the second thing is that dictionary is in an array (I have named it Main Array in the image). To get the JSON string what I should have done is first pull out the object ( here Dictionary) from the array then take the JSON string from the object to parse. For doing this I should have done

NSString *jsonString=[[self.serverAry objectAtIndex:0] valueForKey:@"List"] (process1)

but instead of doing it  I did

NSString *listAry=[self.serverAry valueForKey:@"List"];

as a result I was getting an object inside of an array. (like Image 2) .

Image 2 : Got the json string inside an array

So definitely it is not a JSON string. To correct this either you can use process 1 or just pull the object from this array using objectAtIndex. Like

NSString *listAry=[[self.serverAry valueForKey:@"List"] objectAtIndex:0];

Both processes are right. But if you main array has more than one object then you have to follow the process 1. Otherwise, the compiler will be confused and then it will throw another exception or error. So, I will suggest using the process 1. After getting the JSON string I have just parsed it. Then the output looked like Image 3.

Image 3: After parsing the JSON string got this output

People learn new things from their mistakes. I did the same. So do not be afraid to do mistakes. Just learn from them. 😉

If my post helped you please like and share. 😊

No comments:

Post a Comment