Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSJSONSerialization from NSString

Is it possible if I have a NSString and I want to use NSJSONSerialization? How do I do this?

like image 579
aherlambang Avatar asked Jan 13 '12 23:01

aherlambang


People also ask

What is NSJSONSerialization?

An object that converts between JSON and the equivalent Foundation objects.

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.


2 Answers

First you will need to convert your NSString to NSData by doing the following

NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding]; 

then simply use the JSONObjectWithData method to convert it to JSON

id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
like image 190
Jakub Arnold Avatar answered Sep 29 '22 05:09

Jakub Arnold


You need to convert your NSString to NSData, at that point you can use the +[NSJSONSerialization JSONObjectWithData:options:error:] method.

NSString * jsonString = YOUR_STRING; NSData * data = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError * error = nil; id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (!json) {     // handle error } 
like image 28
sho Avatar answered Sep 29 '22 07:09

sho