1

I have a class with data as follows

Class1 *obj = [[Class1 alloc] init];
obj.One=@"1";
obj.Two=@"2";
obj.Three=@"3";

I want to convert this object into

{"One":"1","Two":"2","Three":"3"}

How Can I do that in Objective C ?

user2971263
  • 93
  • 2
  • 8
  • @OP: you'd be better off using one of the already available automatic serializers. –  Nov 09 '13 at 06:33

1 Answers1

1

You will have to write an instance method for your class to serialize the data (ie: convert the member variables into valid JSON data) and you may want another method to parse JSON data back into the class.

If you're wondering if there is a standard method somewhere to do this for you, the short answer is no -- Since class member variables can be of any object type, they must first be converted to valid JSON data types. (String, number, boolean, array or dictionary)

In your example, this would entail creating a dictionary like this:

NSDictionary *dictionary = @{@"One" : obj.One, @"Two" : obj.Two, @"Three" : obj.Three};

Then you will need to use the NSJSONSerialization class to convert the NSDictionary into a valid JSON string.

stackunderflow
  • 754
  • 7
  • 18