How to Convert a Objective C class into JSON object? [duplicate] - objective-c

This question already has answers here:
Serialize and Deserialize Objective-C objects into JSON
(7 answers)
Closed 9 years ago.
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 ?

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.

Related

Why does NSDictionary uses = sign inside json objects? [duplicate]

This question already has answers here:
Generate JSON string from NSDictionary in iOS
(14 answers)
Closed 8 years ago.
I am creating a new JSON (NSDictionary) object in Objective-C using various methods such
objectForKey
but when I actually print the NSDictionary object after converting it to NSString, I see that unlike the colon (:) separator, it uses the equals (=) separator between the key and value.
How can I ensure that the NSDictionary uses the : as a separator between the key and value?
It is just a formatting issue. If you create an NSJSON obkect from it, that object will be in correctly formatter JSON. When you log NSDictionary to console or otherwise print it, it uses some custom formatting, probably unrelater to the actual internal structure.

Problems adding key/values to a NSMutableDictionary [duplicate]

This question already has answers here:
Editing an NSMutableDictionary sub-dictionary
(2 answers)
Closed 8 years ago.
Fairly new to this. I am trying to add some value/keys to an array that already has value/keys.
The itemsArray contains the json and is derived from the variable json which is a parameter passed to the method from a rest api call.
This is the code I am using and it aborts (at [i setobject] with [__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
NSMutableDictionary *itemsArray = [json objectForKey:#"items"];
for ( NSMutableDictionary *i in itemsArray) {
[i setObject:#"FirstValue" forKey:#"parents"];
}
All this should do is add in the key called parents for each item in the dictionary.
Now if I hard code the value/keys to the mutable dictionary itemsArray - it works fine. Its just when I use the variable json which is passed as a parameter and obtained from a call to a rest api. So the issue is likely that itemsArray contains a immutable json object even though itemsArray is mutable.
The question I have is how do I make the json object mutable (assuming that will cure it) so it will work. ?
You have the answer right in the error message: itemsArray is a NSDictionary not an NSMutableDictionary. See the answer to What is an NSCFDictionary? for more details.
How did you create json? You need to make sure it contains an NSMutableDictionary for the key #"items".
You will need to create a mutable dictionary from your itemsArray. Something like:
NSMutableDictionary *mutableDictionary = [i mutableCopy];
You can then add objects to it as you'd like.

Is there any way to get a property's type in Objective-C? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to detect a property return type in Objective-C
Is there any way to get a property's type in Objective-C? I can access the property like this:
objc_property_t* properties = class_copyPropertyList(cl, &count);
And get the name like this:
property_getName(properties[i]);
What I need to do though is get the type. Also, the value will be nil in most cases so I can't just get the value calling object_getClass().
Not in the sense that you seem to be asking — in Objective-C classes are typeless; when dealing with non-C types beyond 'it's a class' the type of properties isn't known at runtime. That's why if you do something silly like the following in a view controller:
[self setValue:#3 forKey:#"view"];
You'll see an exception raised when the controller attempts to send a view message to the NSNumber rather than by the key-value coding mechanisms because you tried to put something that isn't a view into in an inappropriate property.
Parsing property_getAttributes will allow you to go no further than distinguishing the various C literal types from an Objective-C object type.

Using the value of a string to cast an object

I have to cast an object to a type which is contained in a string and I don't know if it's possible.
My class is in a string :
NSString *myClass = #"User";
and I have an object that I want to cast with this type.
object = (myClass)object; // Doesn't work
object = (myClass *)object; // Doesn't work
How can I do that ?
There's no point to doing this — objects' static types only get checked at compile time, and this could only happen at runtime even if there were a way to do it (since objects such as strings don't actually exist until runtime).
If you're trying to change the object from one class to another, that wouldn't work anyway — casting from one pointer type to another only lies to the compiler about what type of data it points to, it doesn't actually change the data. In order to convert objects from one type to another, there has to be a method or function that takes the data from the old object and creates a new object of the desired type (such as NSString's dataUsingEncoding: to convert from NSString to NSData).
But if you have a dynamically selected class and you need some type to give the variables for instances of that class, you can just use id (possibly with a protocol if all the possible classes respond to the same messages).

What is the preferred datatype to parse JSON into in Objective-C?

What is the preferred datatype to parse JSON into in Objective-C? I'm looking for a data type that mirrors the ability to use key=>value style and just array form.
Typically libraries (such as SBJson) will return their parsed results as either an NSArray or an NSDictionary, just depending on if the parsed JSON element was an object or an array.
From SBJsonParser.h:
/**
#brief Return the object represented by the given string
This method converts its input to an NSData object containing UTF8 and calls -objectWithData: with it.
#return The NSArray or NSDictionary represented by the object, or nil if an error occured.
*/
- (id)objectWithString:(NSString *)repr;
In your question you asked "I'm looking for a data type that mirrors the ability to use key=>value", that is by definition exactly what a dictionary is... so, you're probably looking for NSDictionary.
The question doesn't make any sense. The JSON string itself determines what type of object you are going to get when it's deserialized. It can be a string, number, array or dictionary. You have to be prepared to receive any of those. If you use NSJSONSerialization, you'll notice that the decoding methods return id, which means you don't know the type ahead of time. You will have to use isKindOfClass: to figure out what you actually got back.