5

I have to generate a json string dynamically and need to send to the server. Is any body know how to do it using NSJSONSerialization . Below is my string

{
    "surveyid": "Survey1",
    "responsetime": "dd/mm/yyyy hh:mm:ss",
    "location": null,
    "surveyresponses": [
        {
            "questionid": "111",
            "responses": [
                {
                    "response": "Good",
                    "optionid": 1,
                    "language": "en"
                }
            ]
        },
        {
            "questionid": "112",
            "responses": [
                {
                    "response": "bad",
                    "optionid": 2,
                    "language": "en"
                }
            ]
        }

    ]
}

How can I create a string.json?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
krishna
  • 175
  • 1
  • 2
  • 6

8 Answers8

4

Set dictionary for Data with JSON object like below:

NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:yourDataDictionary options:NSJSONWritingPrettyPrinted error:&err];

NSLog(@"JSON = %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);

See also this link sending-string-as-json-object

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
3

i totally agree with @Apurv, actually @Paras Joshi give the actual answer to your question...(how to send)

NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setValue:@"Survey1" forKey:@"surveyid"];
[dict setValue:@"responsetime" forKey:@"dd/mm/yyyy hh:mm:ss"];
.
.
.

and then an array forKey @"surveyresponses"... in it again create a dictionary...bla..bla

Please make it clear first what you exactly want... How to send a JSON string / how to generate a JSON value.

learn to accept the answers as well as analyse the answers perfectly, and make your questions clear.

Krish Allamraju
  • 703
  • 1
  • 7
  • 29
  • The best answer seems to be if we combine what you posted here, and then append ParasJoshi 's answer. One shows how to build the dictionary object, the other on how to make it into a string. – Volomike Dec 16 '15 at 23:21
1

If you already have JSON string, you can use it directly.

If you have an object(array and dictionary) and if you want to convert it into json string, use below method of NSJSONSerialization.

NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setValue:@"Survey1" forKey:@"surveyid"];
//Add rest of the details in the dictionary

//Pass the dict in below method
    + (NSData *)dataWithJSONObject:(id)dict options:(NSJSONWritingOptions)opt error:(NSError **)error

Now, use above data to create a string object.

Apurv
  • 17,116
  • 8
  • 51
  • 67
1

Sample code to generate Json String:

 NSString *strdata =[NSString stringWithFormat:@"&data={\"user_id\":\"%@\",\"auth_token\":\"%@\",\"coupon_id\":\"%@\",\"rest_name\":\"%@\",\"name\":\"%@\",\"description\":\"%@\",\"condition\":\"%@\",\"coupon_code\":\"%@\",\"parent_menu_item\":\"%@\",\"discount_item\":\"%@\",\"discount_pecent\":\"%@\",\"start_date\":\"%@\",\"end_date\":\"%@\",\"status\":\"%@\"}",userid,auth_token,couponid,restuserid,txtCoupannm.text,txtvwCoupandesc.text,txtvwcoupancond.text,couponcode,appDelegate.tempparentmenuId,appDelegate.tempdiscountitemId,txtPercent.text,startdate.text,enddate.text,@"1"];
Mat
  • 202,337
  • 40
  • 393
  • 406
V.D
  • 403
  • 1
  • 6
  • 22
1

Try this : if there are more then one item then put (str = ) in loop

    NSString *str = [NSString stringWithFormat:@"json_data={\"data\":["];

    str = [str stringByAppendingString:[NSString stringWithFormat:@"{\"type\":\"%@\",\"surveyid\":\"%@\",\"veriety\":\"%@\",\"responsetime\":\"%@\",\"rate\":\"%@\",\"seeddepth\":\"%@\",\"groundspeed\":\"%@\",\"note\":\"%@\",\"AnhRate\":\"%@\",\"AnhVarRate\":\"%@\",\"WetRate\":\"%@\",\"WetVarRate\":\"%@\",\"WetType\":\"%@\",\"DryRate\":\"%@\",\"DryVarRate\":\"%@\",\"DryType\":\"%@\",\"MicroRate\":\"%@\",\"MicroVarRate\":\"%@\",\"MicroType\":\"%@\",\"NoteApp\":\"%@\",\"userid\":\"%@\",\"flid\":\"%d\",\"catid\":\"%d\",\"subcatId\":\"%d\",\"categoryname\":\"%@\",\"subcategoryname\":\"%@\",\"activitydate\":\"%@\",\"DateCreated\":\"%@\",\"DateUpdated\":\"%@\"},",Your variable

    if ([str length] > 0) {
            str =[str substringToIndex:[str length] - 1];
    }

str = [str stringByAppendingString:@"]}"];
SAMIR RATHOD
  • 3,512
  • 1
  • 20
  • 45
1

I had to build something similar and applied what I did to your string - it may not be the best way to achieve the result, but it worked for me. For the inner survey responses array (in my case it was a different array), I simply chained several together.

NSString *ts=@"2015-04-03T13:00:00";
    NSString *outer = [NSString stringWithFormat: @"{\"surveyId\":\"Survey1\", \"responsetime\":\"%@\", \"location\":\"%@\", \"surveyresponses\":[{\"", ts, @"null"];


    NSString * surveyresponse = [NSString stringWithFormat: @"questionid\":\"111\", \"responses\":[{\"response\":\"good\", \"optionid\":\%d\, \"language\":\"en\"}]", 1];

    NSString *ending = @"}]}";

    NSString *jsonStr = [NSString stringWithFormat:@"%@%@%@", outer, surveyresponse, ending];

    NSData * postdata = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];

    NSError * error = nil;
    id json = [NSJSONSerialization JSONObjectWithData:postdata options:0 error:&error];

    if (!json) {
        // handle error
        NSLog(@"json string error - %@", error.description);
    }
    NSLog(@"%@",[[NSString alloc] initWithData:postdata encoding:NSUTF8StringEncoding]);
JanB
  • 904
  • 9
  • 14
0

Assuming that you already have the JSON in an NSString, you can save it to a file by calling:

[jsonString writeToFile:@"/path/to/JSON.json" atomically:YES encoding:NSASCIIStringEncoding error:nil]

The documentation for this function is here.

drewmm
  • 737
  • 6
  • 17
0
NSDictionary* jsonResp = [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&error];
Nimantha
  • 6,405
  • 6
  • 28
  • 69
kowshik
  • 9
  • 3