2013-03-20 51 views
4

我必须动态生成一个json字符串并需要发送到服务器。有没有人知道如何使用NSJSONSerialization。以下是我的字符串在目标中创建一个json字符串C

{ 
    "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,请帮助,如果有人知道。提前致谢。

回答

2

我完全同意@Apurv, 实际上@Paras乔希给实际的回答你的问题......(如何发送)

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值。

学会接受答案并完美分析答案,并明确问题。

+0

最好的答案似乎是如果我们结合你在这里发布的内容,然后附加ParasJoshi的答案。其中一个显示如何构建字典对象,另一个显示如何将其设置为字符串。 – Volomike 2015-12-16 23:21:02

0

假设你已经有了JSON在NSString,您可以通过调用其保存到一个文件:

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

这个函数的文档here

+0

我需要从scracth生成像上面那样的jstring字符串 – krishna 2013-03-20 06:45:57

+0

您是从头开始的什么意思?你有'NSDictionary'对象中的数据吗?如果不是,您从哪里获取数据? – drewmm 2013-03-20 06:48:10

1

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

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

+0

我需要从scracth生成类似于上面的jstring字符串 – krishna 2013-03-20 06:46:36

+0

首先创建字典。添加适当的键值,然后使用上面的函数。 – Apurv 2013-03-20 06:48:56

+0

查看已更新的答案。 – Apurv 2013-03-20 06:52:51

3

刚刚成立字典数据和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

我希望这对您有所帮助..

+0

@krishna看到这个链接也适当的字典.. http://stackoverflow.com/questions/11882696/create-a-jsonstring-in-ios – 2013-03-20 07:28:48

1

示例代码来生成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"]; 
0

试试这个:如果有多于一个项目然后把(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:@"]}"]; 
0

试试这个代码,它可能是有用ü......

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

我必须建立类似的东西应用于我因你的字符串 - 它可能不会达到最好的方法结果,但它为我工作。对于内部调查响应数组(在我的情况下它是一个不同的数组),我只是将几个链接在一起。

NSString *[email protected]"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]); 
相关问题