iOS: Serialize/Deserialize complex JSON generically from NSObject class

后端 未结 3 720
栀梦
栀梦 2020-11-27 07:45

Anyone have idea how to serialize nested JSON based on NSObject class? There is a discussion to serialize simple JSON here , but it is not generic enough to cater complex n

3条回答
  •  情书的邮戳
    2020-11-27 08:32

    You must know ahead of time what sort of object you will be deserializing. In this case, you're going to be deserializing to an NSDictionary that has two properties: "accounting" and "sales". Each of these properties will be an instance of NSArray. The arrays will have instances of NSDictionary.

    Since you know what each of these objects really are, once you have deserialized the JSON into native objects you can create new instances of your classes out of the deserialized objects. For example:

    JSONDecoder decoder = [[JSONDecoder alloc] init];
    NSObject notJSON = [decoder objectWithData:jsonData];
    // where jsonData is an NSData representation of your JSON
    [decoder release];
    
    Person person1 = (Person)[notJSON objectForKey:@"accounting"][0];
    

    Given this example, you should be able to extrapolate to a more generic deserializer. That is, you'd want to loop through your data to create a deep copy of your "unknown" generic object to a "known" specific object.

提交回复
热议问题