【问题标题】:How can I create a json string in objective C?如何在目标 C 中创建 json 字符串?
【发布时间】:2013-03-09 03:36:45
【问题描述】:

我必须动态生成一个 json 字符串并且需要发送到服务器。有没有人知道如何使用 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?

【问题讨论】:

    标签: iphone ios objective-c json ipad


    【解决方案1】:

    我完全同意@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 值。

    学会接受答案并完美地分析答案,让你的问题清晰。

    【讨论】:

    • 最好的答案似乎是我们结合您在此处发布的内容,然后附加 ParasJoshi 的答案。一个展示了如何构建字典对象,另一个展示了如何将它变成一个字符串。
    【解决方案2】:

    使用 JSON 对象为数据设置字典,如下所示:

    NSError *err;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:yourDataDictionary options:NSJSONWritingPrettyPrinted error:&err];
    
    NSLog(@"JSON = %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
    

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

    【讨论】:

    【解决方案3】:

    如果你已经有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
    

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

    【讨论】:

    • 我需要从 scracth 生成一个像上面这样的 jsonstring
    • 先创建字典。为其添加适当的键值,然后使用上述函数。
    • 我无法为上述真正的 pblm 生成正确的字典
    【解决方案4】:

    试试这个:如果有超过一项,则将 (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:@"]}"];
    

    【讨论】:

      【解决方案5】:

      生成Json字符串的示例代码:

       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】:

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

        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】:

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

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

        这个函数的文档是here

        【讨论】:

        • 我需要从 scracth 生成一个像上面这样的 jsonstring
        • 从头开始是什么意思?你有 NSDictionary 对象中的数据吗?如果没有,您从哪里获取数据?
        【解决方案8】:
        NSDictionary* jsonResp = [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&error];
        

        【讨论】:

          猜你喜欢
          • 2010-11-06
          • 1970-01-01
          • 2015-10-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-04
          相关资源
          最近更新 更多