Parsing JSON to a predefined class in Objective C

后端 未结 5 1515

I have a json string like:

{
  \"a\":\"val1\",
  \"b\":\"val2\",
  \"c\":\"val3\"
}

And I have an objective C header file like:



        
5条回答
  •  迷失自我
    2021-02-02 04:18

    You have two solutions:

    Manual

    Write code to parse the JSON to a dictionary and after populate manually an instance of your target object

    NSDictionary *jsonDictionary = //JSON parser
    
    TestItem *ti = [TestItem new];
    ti.a = [jsonDictionary objectForKey:@"a"];
    ti.b = [jsonDictionary objectForKey:@"b"];
    ti.c = [jsonDictionary objectForKey:@"c"];
    

    iOS provides you a json parser. Look at this reply for more infos How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

    (you should also check that the objects type match your expectations and eventually manage properly cases of error)

    Mapping lib

    Use a mapper library like JTObjectMapping that can help you to define how your object should be filled using the JSON. Usually I prefer this solution. It automatically checks for types and your code will be clearer.

提交回复
热议问题