Talha Ch Talha Ch - 1 month ago 7
Objective-C Question

Making Nested JSON in NSDictionary from CoreData

I don't know if the title goes exactly with the question or not but if you feel it's missing something kindly edit the question.
I want to send parameter in specific format like

JSON
to
AFNeworking
in order to save the data on server.

I've an
NSArray
in which is named
fetchedDX
and I'm loading it with values from CoreData as
fetchedDX = [Diagnoses MR_findAllWithPredicate:predicate];
which is getting the right values as I'm using it's count at one place and it is giving me the right count. This is the hardcode NSDictionary I'm preparing to send:

NSDictionary *superBillData = @{
@"appointmentID": @"ABC",
@"patientID": @"ABC",
@"createdBy": @"ABC",
@"lastChangedBy": @"ABC",
@"Diagnoses":@[
@{
@"Code":@"hello world",
@"shortDescription": @"my@you.com"
},
@{
@"Code":@"hello 2",
@"shortDescription": @"Lorem Ipsum"
},
]};


Here the
Diagnoses
key is the one sending multiple objects. Now I've this data in
fetchedDX
array as core data gave me but I don't know how to make a dynamic
NSDictionary
because this array can have a count of one or more than one. So based on every value I've to create this:

@{
@"Code":@"hello world",
@"shortDescription": @"my@you.com"
}


Here is the picture of my entity:

enter image description here

Any ideas how can this be achieved?

Answer

I assume that Code and shortDescription are the attributes of your Diagnoses entity. In the Diagnoses.h declare an instance method - (NSDictionary *)dictionary; and do this in your Diagnoses.m file.

- (NSDictionary *)dictionary {

    NSArray *keys = @[@"Code", @"codeDescription"];
    NSDictionary *dict = [self dictionaryWithValuesForKeys:keys];

    return dict;
}

Then where you prepare the parameters dictionary change your code to this.

NSMutableArray *diagnosesArray = [NSMutableArray array];

    for (Diagnoses *obejct in fetchedDX) {
        [diagnosesArray addObject:[obejct dictionary]];
    }

    NSDictionary *superBillData = @{
                                    @"appointmentID": @"ABC",
                                    @"patientID": @"ABC",
                                    @"createdBy": @"ABC",
                                    @"lastChangedBy": @"ABC",
                                    @"Diagnoses":diagnosesArray};
Comments