-->

Create a json string in objective C

2020-07-16 05:52发布

问题:

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 create a string.json , Please help if any one know. Thanks in advance.

回答1:

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.



回答2:

just set dictionary for Data with JSON object like bellow

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

i hope this helpful to you..



回答3:

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.



回答4:

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:@"]}"];


回答5:

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"];


回答6:

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]);


回答7:

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.



回答8:

try this code it may be useful for u......

NSDictionary* jsonResp = [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&error];