Converting JSON to Objective-C object using key value coding - objective-c

I am an Objective-C newbie coming from the Java world, so I am trying to find out how to do something that would be (relatively) straightforward to do in Java.
In an iPhone app I am accessing a rest webservice that returns JSON. I am using the AFNetworking framework, which provides support for using the NSJSONSerialization class added to iOS 5. I would like to know if there is an "automatic" way to turn the JSON object that is returned into one of my "strongly" typed classes (for example, my UserAccount class).
In other words, I'm trying to do something like:
id json = ... call webservice that returns json, which AFNetworking parses ...
UserAccount myUserAccount = [UserAccount alloc] init];
//then here I'd like something that iterates through all the properties on the
//json object and sets them on the myUserAccount object using key value coding
Is there a straightforward way to accomplish this?

Nope, not that I know of. The most common way is to add a constructor to your class called initWithDictionary, that accepts the JSON dictionary and gets the relevant information from it.

Related

Providing my own objects for "make new" in my scriptable application

This is a question about implementing a scriptable application using Cocoa Scripting.
My app's scriptable application object contains elements of a custom class, let call it flower.
In the .sdef file, the Cocoa class for flower is specified as ScriptableFlower.
In Applescript, one can now write:
tell app "myapp"
get flowers
end tell
My code provides an accessor function for retrieving flowers: -(NSArray*)flowers.
Now, I like to implement a way to add new flowers, so that one can write:
tell app "myapp"
make new flower
end tell
The default behavior for this, with the default Core suite handler for "make" using NSCreateCommand, is as follows:
The scripting engine will fetch the current array of flowers by calling my flowers function, then instantiate a new Cocoa object of class ScriptableFlower, and then call setFlowers:(NSArray*) with an array that contains my original objects plus the newly created one.
However, this is not good for my application: I cannot allow the scripting engine to create objects of my scriptable classes at will.
Instead, I need to be the one instantiating them.
A half-way solution would be to implement the default -(id)init method and then detect if it's called by me - if not, I can take the extra steps. But that's not clean. I rather do not let the scripting engine create new objects at all but rather provide them myself as I may have the object "somewhere" already prepared.
Is there some provision in Cocoa Scripting that leads to it calling me whenever it wants me to create a new scriptable object?
Update
To clarify: The Cocoa Scripting docs explains that one can implement special insertion handlers (insertObject:in<Key>AtIndex:)so that one doesn't have to take the entire NSArray, but that still leads to the scripting engine to create the object. I need to be asked to create the object instead, though.
The file NSObjectScripting.h provides a function for this:
- (id)newScriptingObjectOfClass:(Class)objectClass forValueForKey:(NSString *)key withContentsValue:(id)contentsValue properties:(NSDictionary *)properties;
It's available since OS X 10.5 and documented as follow:
Create a new instance of a scriptable class to be inserted into the relationship identified by the key, set the contentsValue and properties of it, and return it. Or return nil for failure. The contentsValue and properties are derived from the "with contents" and "with properties" parameters of a Make command. The contentsValue may be nil. When this method is invoked by Cocoa neither the contentsValue nor the properties will have yet been coerced using scripting key-value coding's -coerceValue:forKey: method. In .sdef-declared scriptability the types of the passed-in objects reliably match the relevant .sdef declarations however.
One option is to subclass NSCreateCommand and implement your own logic.

convert an object to JSON in objective c

I work in tool theos projects and i want convert an object into JSON.
I need a easy to use library with examples for converting NSObjects to JSON and back again
I check a lot of question like this but i can't use them.
I use JSONModel library but i have a lot of errors.
Anybody body have a good tutorial or a sample code to convert NSObject to JSON?
I don't have any idea whether I can created a json or not.
How can I fix this?
Look at my library - https://github.com/DimasSup/BaseMangedObjectModel
With it you can serialize/deserialize any your class. aslo can save it to SQLite database if needed. Also there are NetworkHelper class which help you send/receive your classes from remote server.

How to convert JSON object to Objective-C Cocoa object?

Am developing a cocoa application, where I have to invoke java web scripts and fetch the response of the web script object and convert it into Objective C readable objects. I would then need to manipulate the fetched data for import, print, etc.
How to I interact with the web script and convert into cocoa readable objects?
Any pointers on the same, will be appreciated.
Thanks,
Nana
Convert the JSON string into an NSDictionary using tools like yajl, JSONKit or iOS5 JSON
Use https://github.com/elado/jastor to convert this NSDictionary to a real Objective-C class with typed properties, nested properties, arrays etc.
In iOS 5 native JSON parsing is supported (documentation). In addition you can use a number of third party libraries to download and parse JSON (see JSONKit and HTTPRiot or RestKit)
A full reference of awesome libraries can be found here.

Creating an Objective-C API

I have never made an API in objective-c, and need to do this now.
The "idea" is that I build an API which can be implemented into other applications. Much like Flurry, only for other purposes.
When starting the API, an username, password and mode should be entered. The mode should either be LIVE or BETA (I guess this should be an NSString(?)), then afterwards is should be fine with [MyAPI doSomething:withThisObject]; ect.
So to start it [MyAPI username:#"Username" password:#"Password" mode:#"BETA"];
Can anyone help me out with some tutorials and pointer on how to learn this best?
It sounds like what you want to do is build a static library. This is a compiled .a file containing object code that you'll distribute to a client along with a header file containing the interface. This post is a little outdated but has some good starting points. Or, if you don't mind giving away your source code, you could just deliver a collection of source files to your client.
In terms of developing the API itself, it should be very similar to the way you'd design interfaces and implementations of Objective-C objects in your own apps. You'll have a MyAPI class with functions for initialization, destruction, and all the functionality you want. You could also have multiple classes with different functionality if the interface is complex. Because you've capitalized MyAPI in your code snippet, it looks like you want to use it by calling the class rather than an instance of the class - which is a great strategy if you think you'll only ever need one instance. To accomplish this you can use the singleton pattern.
Because you've used a username and password, I imagine your API will interface with the web internally. I've found parsing JSON to be very straightforward in Objective-C - it's easy to send requests and get information from a server.
Personally I would use an enum of unsigned ints rather than a NSString just because it simplifies comparisons and such. So you could do something like:
enum {
MYAPI_MODE_BETA,
MYAPI_MODE_LIVE,
NUM_MYAPI_MODES
};
And then call:
[MyAPI username:#"Username" password:#"Password" mode:MYAPI_MODE_BETA];
Also makes it easy to check if they've supplied a valid mode. (Must be less than NUM_MYAPI_MODES.)
Good luck!

Intercepting Method Access on the Host Program of IronPython

Greetings,
Most of the information I see around concerning the construction of Proxies for objects assume that there exists a Type somewhere which defines the members to be proxied. My problem is: I can't have any such type.
To make the problem simpler, what I have is a dictionary that maps strings to objects. I also have getters and setters to deal with this dictionary.
My goal then is to provide transparent access inside IronPython to this getters and setters as if they were real properties of a class. For example, the following code in a python script:
x.result = x.input * x.percentage;
...would actually represent something like in the host language:
x.SetProperty("result", x.GetProperty("input") * x.GetProperty("percentage"));
Also, 'x' here is given by the host program. Any ideas? Please remember that I cannot afford the creation of a typed stub... Ideally, I would be happy if somehow I could intercept every call to an attribute/method of a specific object in the script language onto the host program.
This post might be useful.