I defined some custom classes, such as Teacher, Student…
Now I receive teacher info (JSON string) from remote server.
How can I convert the JSON string to Teacher object.
In Java, it’s easy to implement a common method for all class (Teacher, Student…) with reflect.
But in Objective-C on iOS, the best way I can find is to use Entity of Core Data, which has setValue:forKey method. First I convert the JSON string to NSDictionary, the set the key-value pair in the disctionary to the Entry.
Is there any better ways?
(I’m from China, so maybe my English is poor, sorry!)
These are all good frameworks for JSON parsing to dictionaries or other primitives, but if you’re looking to avoid doing a lot of repetitive work, check out http://restkit.org . Specifically, check out https://github.com/RestKit/RestKit/blob/master/Docs/Object%20Mapping.md This is the example on Object mapping where you define mapping for your Teacher class and the json is automagically converted to a Teacher object by using KVC. If you use RestKit’s network calls, the process is all transparent and simple, but I already had my network calls in place and what I needed was to convert my json response text to a User object (Teacher in your case) and I finally figured out how. If that’s what you need, post a comment and I’ll share how to do it with RestKit.
Note: I will assume the json is output using the mapped convention
{"teacher": { "id" : 45, "name" : "Teacher McTeacher"}}. If it’s not this way, but instead like this{"id" : 45, "name" : "Teacher McTeacher"}then don’t worry … object mapping design doc in the link shows you how to do this…a few extra steps, but not too bad.This is my callback from ASIHTTPRequest
You can obviously refactor this to make it cleaner, but that now solves all my problems.. no more parsing… just response -> magic -> Object