Search code examples
iosobjective-cjsonnsarray

Setting data in correct JSON format using Array and Dictionary


Below is the model for which I have to set the data. I am using array and dictionary to achieve this, Here is the code which I tried. But its giving me the output which is invalid JSON.
One more thing I want to ask is why the log of an array starts and ends with small braces?
Any help would be much appreciated.

Code:

NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
                       parameterName,@"parameterName",
                       parameterType, @"parameterType",
                       [NSNumber numberWithBool:parameterSorting],@"parameterSorting",[NSNumber numberWithBool:parameterSorting],
                       @"parameterOrdering",
                       nil];

NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
NSDictionary *paramData = @{@"rqBody":@{@"catalogName":@"",@"userId":@"", @"parameter":paramArray, @"catalogMode":@""}};

NSData *postData = [NSKeyedArchiver archivedDataWithRootObject:paramData];`

Output:

{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":"(
        {
        parameterName = anandShankar;
        parameterOrdering = 1;
        parameterSorting = 1;
        parameterType = Text;
    }
)","catalogMode":"xxxxxx"}}

Desired Output:

{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":[{
        "parameterName" : "anandShankar",
        "parameterOrdering" : 1,
        "parameterSorting" : 1,
        "parameterType" : "Text"
    }],"catalogMode":"xxxxxx"}}

Solution

  • Try this code :

    NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
            @"Object1",@"parameterName",
            @"Object2", @"parameterType",
            @'Object3',@"parameterSorting",@"Object4",
            @"parameterOrdering",
                    nil];
    NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
    
    NSDictionary *paramData = @{@"rqBody":@{@"catalogName":@"",@"userId":@"", @"parameter":paramArray, @"catalogMode":@""}};
    

    Add this lines :

    NSError * err;
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:paramData options:0 error:&err];
    NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@", myString); // it will print valid json 
    

    JSON

    {  
      "rqBody":{  
         "catalogName":"",
         "parameter":[  
            {  
               "parameterOrdering":"Object4",
               "parameterName":"Object1",
               "parameterType":"Object2",
               "parameterSorting":51
            }
         ],
         "userId":"",
         "catalogMode":""
      }
    }