Sunday, October 9, 2016

How to check a valid JSON string Objective-C

Today I am going to discuss how to check a string is a valid JSON string.

Suppose, after calling a API you got a JSON string like [{\"ColOne\":\"ABC\",\"ColTwo\":\"\123\"}].  Now you need to check if it is a valid JSON or not. You can do this checking with NSJSONSerialization. Just try to Serialized the Data you are getting from JSON string. If it does not return an error that means the string is a valid JSON string. Just have a look at Image 1(a) and the output for this snippet is in Image 1(b).


Image 1(a): Checking valid JSON snippet
In Image 1(a), trying to Serialized the response string.






Image 1(b): Output for valid JSON

The response string was a valid JSON string. So in the serialization it did not send error. Image 1(b)




Now just change the responseString  to "Hello there". You can see the output in the Image 2.


Image 2: Output for Invalid JSON

Code snippet:
NSString *responseString =@"[{\"ColOne\":\"ABC\",\"ColTwo\":\"\123\"}]";
   NSData *responseData=[responseString dataUsingEncoding:NSUTF8StringEncoding];

   NSError *error;
   if([NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error] == nil){
     NSLog(@"not a valid json");
   } else{
     NSLog(@"valid json");
   }

No comments:

Post a Comment