繁体   English   中英

在目标C中创建一个json字符串

[英]Create a json string in objective C

我必须动态生成一个json字符串,并需要发送到服务器。 有没有人知道如何使用NSJSONSerialization来做到这NSJSONSerialization 下面是我的字符串

{
    "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"
                }
            ]
        }

    ]
}

如何创建一个string.json,如果有人知道请帮助。 提前致谢。

只需为像Jlow对象设置数据字典,如bellow

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

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

另请参见此链接sending-string-as-json-object

我希望这对你有帮助..

我完全赞同@Apurv,实际上@Paras Joshi给出了你问题的实际答案......(如何发送)

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

然后一个数组forKey @"surveyresponses" ...再次创建一个字典... bla..bla

请首先说明您的确切需求...如何发送JSON字符串/如何生成JSON值。

学会接受答案并完美分析答案,并清楚地提出问题。

如果您已经有JSON字符串,则可以直接使用它。

如果您有一个对象(数组和字典),并且如果要将其转换为json字符串,请使用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

现在,使用上面的数据来创建一个字符串对象。

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

试试这个:如果有多个项目,则将(str =)放入循环中

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

我必须构建类似的东西并将我所做的应用到你的字符串中 - 它可能不是实现结果的最佳方式,但它对我有用。 对于内部调查响应数组(在我的情况下,它是一个不同的数组),我只是将几个链接在一起。

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

假设您已经在NSString拥有JSON,可以通过调用以下命令将其保存到文件中:

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

此功能的文档在这里

尝试这段代码它可能对你有用......

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM