Create a json string in objective C

2020-07-16 06:27发布

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.

8条回答
劳资没心,怎么记你
2楼-- · 2020-07-16 06:30

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

NSDictionary* jsonResp = [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&error];
查看更多
神经病院院长
3楼-- · 2020-07-16 06:31

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.

查看更多
你好瞎i
4楼-- · 2020-07-16 06:37

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.

查看更多
smile是对你的礼貌
5楼-- · 2020-07-16 06:40

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]);
查看更多
Summer. ? 凉城
6楼-- · 2020-07-16 06:44

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:@"]}"];
查看更多
可以哭但决不认输i
7楼-- · 2020-07-16 06:50

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..

查看更多
登录 后发表回答