字典转为json的方法

该博客介绍了如何将Objective-C中的字典转换为JSON字符串。提供了一个名为`jsonFromDictionary:`的方法,用于将字典转换成JSON数据,然后转化为NSString。文中展示了如何创建并填充字典,最后将字典添加到另一个字典中,生成最终的JSON表示。如果需要,还考虑了在JSON中包含特定键值的情况。
摘要由CSDN通过智能技术生成

用处:把用户输入的表单值放入字典,字典在转json传

方法:

+ (NSString*)jsonFromDictionary:(NSDictionary*)dict

{

    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];

    return [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];

}


用法:


    NSDictionary* curBank = cgyhArr[currentCGXYView.tag];

    NSMutableDictionary* dictcg = [[NSMutableDictionary alloc] init];

    

    [dictcg setValue:_inputValues[2] forKey:@"YHZH"];

    [dictcg setValue:_inputValues[3] forKey:@"YHMM"];

    [dictcg setValue:@"1" forKey:@"ZZHBZ"];//指定行币种

    [dictcg setValue:@"1" forKey:@"BZ"];//币种

    [dictcg setValue:[curBank valueForKey:@"YHDM" ] forKey:@"YHDM"];//银行代码

    

    NSMutableDictionary* dictxy = [[NSMutableDictionary alloc] init];

    [dictxy setValue:[curBank valueForKey:@"XYID"forKey:@"HTXY"];//合同协议

    [dictxy setValue:@"" forKey:@"XYBH"];//协议编号

    [dictxy setValue:qmlsh forKey:@"QMLSH"];//签名流水号

    

    NSMutableDictionary* json = [[NSMutableDictionary alloc] init];

    [json setValue:@[dictcg] forKey:@"CGYHSTR"];

    [json setValue:@[dictxy] forKey:@"CGXYSTR"];

    if (_isReAssign) {

        [json setValue:[_khzt valueForKey:@"bdid"] forKey:@"BDID"];

    }

    return [SSUtility jsonFromDictionary:json];




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值