0

I am using JSONModel in my application. Is it possible to prepare category with JSONValueTransformer that will transform nil/null NSString to empty string (@""). So far when property in json response is null, my property in object becomes @"".

Because the whole API is not very well (it's external) I would like to avoid overriding initWithDictionary in every object and use just ValueTransformer for every JSONModel class with NSString property and map it to correct string or empty string if nil/null.

Piotr Gawłowski
  • 189
  • 1
  • 10
  • Instead of converting the API's response from `NSNull`s to empty `@""` why don't you just handle the `nil` case in your app? Working with `nil` is nothing new in Obj-C Seems to me that an API that returns an `NSNull` when the string property doesn't have a value, is the right thing to do. – Aaron Feb 02 '16 at 22:21
  • First of all I was trying to do it from ValueTransformer side as an educational issue - to check the possibilities of this approach. Handling it in app will require to check [NSString isNotNullOrEmpty] in every single label I'm settings in app with data from api and belive me this app is really huge. So the question is: is above issue possible or do you know better approach to handle it in whole app without handling so many if() cases? – Piotr Gawłowski Feb 03 '16 at 08:35
  • Yes, sure its possible to put a category on `NSDictionary` or `ValueTransformer` that filters out `NSNull` and replaces them with `@""`. – Aaron Feb 03 '16 at 17:20

1 Answers1

0

After getting response, run following loop with your response dictionary and its key.

for (id dictionary in [[responseDictionary valueForKey:@"responseKey"] allKeys] )
    {
           ([[responseDictionary valueForKey:@"responseKey"] valueForKey:dictionary] == [NSNull null]) ? [[responseDictionary valueForKey:@"responseKey"] setValue:@"" forKey:dictionary] :[[responseDictionary valueForKey:@"responseKey"] setValue:[[responseDictionary valueForKey:@"responseKey"] valueForKey:dictionary] forKey:dictionary];
    }
Hima
  • 1,249
  • 1
  • 14
  • 18