SoFunction
Updated on 2025-03-10

Objective-C Json instance detailed explanation

Objective-C Json instance detailed explanation

By using NSJSONSerialization, you can convert Json and Foundation into each other. The following details the use of Objective-c json.

Json To Fundation

Use JSONObjectWithData to convert Json to Foundation. The top layer of Json can be {} or [] so it can have two formats: NSDictionary and NSArray. Reading uses ObjectForKey to return the corresponding object.

NSString* items = @"{"items":["item0","item1","item2"]}";
 
NSData *data= [items dataUsingEncoding:NSUTF8StringEncoding];
 
NSError *error = nil;
 
id jsonObject = [NSJSONSerialization JSONObjectWithData:data 
          options:NSJSONReadingAllowFragments 
          error:&error];
 
if ([jsonObject isKindOfClass:[NSDictionary class]]){
 
  NSDictionary *dictionary = (NSDictionary *)jsonObject;
 
  NSLog(@"Dersialized JSON Dictionary = %@", dictionary);
 
}else if ([jsonObject isKindOfClass:[NSArray class]]){
 
  NSArray *nsArray = (NSArray *)jsonObject;
 
  NSLog(@"Dersialized JSON Array = %@", nsArray);
 
} else {
 
  NSLog(@"An error happened while deserializing the JSON data.");
 
}
 
NSDictionary *dict = (NSDictionary *)jsonObject;
 
NSArray* arr = [dict objectForKey:@"items"];
NSLog(@"list is %@",arr);

Fundation To Json

Use dataWithJsonObject to convert Fundation to Json. where options:NSJSONWritingPrettyPrinted is branch output json, and the output without spaces uses option:kNilOptions.

The following code is a list of products obtained by IOS in-app purchase. Once fetched, add the content to Json.

NSArray *myProduct = ;
NSDictionary *myDict;
NSMutableDictionary *dict = [NSMutableDictionary 
                dictionaryWithCapacity: 4];
 
for(int i = 0;i<;++i)
{
 
  //NSLog(@"----------------------");
  //NSLog(@"Product title: %@" ,[myProduct[i] localizedTitle]);
  //NSLog(@"Product description: %@" ,[myProduct[i] localizedDescription]);
  //NSLog(@"Product price: %@" ,[myProduct[i] price]);
  //NSLog(@"Product id: %@" ,[myProduct[i] productIdentifier]);
 
  myDict = [NSDictionary dictionaryWithObjectsAndKeys:
          [myProduct[i] localizedTitle], @"title",
          [myProduct[i] localizedDescription], @"desc",
          [myProduct[i] price], @"price",
          [myProduct[i] productIdentifier], @"product", nil];
 
  [dict setValue: myDict forKey: [myProduct[i] productIdentifier]];
}
if([NSJSONSerialization isValidJSONObject:dict])
{
  NSError* error;
  NSData *str = [NSJSONSerialization dataWithJSONObject:dict 
            options:kNilOptions error:&error];
  NSLog(@"Result: %@",[[NSString alloc]initWithData:str 
              encoding:NSUTF8StringEncoding]);
}
else
{
  NSLog(@"An error happened while serializing the JSON data.");
}    

If you have any questions, please leave a message or go to the community of this site to exchange and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!