开发者

Objective C - Data Binding?

I am trying to create a JSON library that converts JSON string into objects. What's the cleanest way to mark properties that are related to JSON string? Is it possible to achieve something like the code below

NOTE: The code below doesn't work it's just a sample to show what I'm trying to achieve

JSON String

{
   "FIRST_NAME": "Some first name",
   "LAST_NAME":  "Some last name"
   "CLASSES" : 
   [
      {
         "CLASS_NAME": "class 1"
      }
      {
         "CLASS_NAME": "class 2"
      }
   ]
}

Model

@interFace Student

[JSON = "FIRST_NAME"]
@property (nonatomic, retain) NSString *firstName;

[JSON = "LAST_NAME"]
@property (nonatomic, retain) NSString *lastName;

[JSON = "CLASSES"]
@property (nonatomic, retain) NSArray  *classes;

@end

JSON Method

@implementation JSON
+ (id)getObjectFromJSONString:(NSString*)string withType:(Class)class
{
   //Create a student Object
   //for each property if there is a JSON mark 开发者_JAVA百科look for the value in json string
   //populate all available values
   //return object
}
@end


It is certainly possible. However, note that Objective-C doesn’t support arbitrary source code annotations that can be inspected at runtime, so the mapping between a JSON key and an object key representing an instance variable or declared property won’t be exactly like you’ve described.

I recommend you take a look at RestKit. Besides helping with connecting your program to RESTful services, it has an object mapping infrastructure that turns remote JSON messages into local domain objects in a declarative manner.


I ended up writing a small library for this specific purpose.

https://github.com/aryaxt/OCMapper


I assuming that you are using JSON-Framework to parse JSON.

Not as far as I know. We have been writing a few data clients that consume JSON input.

Depending on who maintains the REST service you also have to check for things like NULL values. Also you might have to covert values to Integer/Float.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜