当前位置:   article > 正文

iOS给H5传值JSON中的转义字符\\\被自动移除问题_andrion给h5传值json中的\字符被自动移除问题

andrion给h5传值json中的\字符被自动移除问题
1、问题

有一个下面的字符串要从iOS传递给H5,该字符串是NSDictionary转化成的JSON字符串

NSString *test= @"{\"result\":\"{\\\"alipay_trade_app_pay_response\\\":{\\\"code\\\":\\\"10000\\\",\\\"msg\\\":\\\"Success\\\",\\\"app_id\\\":\\\"20170703070\\\",\\\"auth_app_id\\\":\\\"2017071007703070\\\",\\\"charset\\\":\\\"utf-8\\\",\\\"timestamp\\\":\\\"2021-01-15 16:20:07\\\",\\\"out_trade_no\\\":\\\"2021011516200100001\\\",\\\"total_amount\\\":\\\"0.01\\\",\\\"trade_no\\\":\\\"2021011522001498171441503742\\\",\\\"seller_id\\\":\\\"2088911950619548\\\"},\\\"sign\\\":\\\"5dIhgjeWwTQZy0Np9ASA048kXVD50TMW6\\/EKLtLjnLmu00aha1FvV28Hh4NC5fK9n54WjueJ9cTBcdUoVRusitDEAFh2QLupnPGvGR1inegiHsPd4U8T\\/AvdKpmU\\/VY\\/jLVX32eOQadGnejYoJLUJv43zI\\/oV8P765+usFxFEvYrrmJx1RiGetuObzFeJoUmCK+s1kc0AE8bxiOVrwfMjPAtRGQ62vqPy6sitaqWds+hdgvyZ\\/cp53pgPV5oWg1jYHTj1jQmA==\\\",\\\"sign_type\\\":\\\"RSA2\\\"}\",\"resultStatus\":\"9000\",\"memo\":\"\"}";
  • 1

结果H5接收到的值被转换成下面

{"result":"{"alipay_trade_app_pay_response":{"code":"10000","msg":"Success","app_id":"2017077703070","auth_app_id":"2017071007703070","charset":"utf-8","timestamp":"2021-01-15 15:43:36","out_trade_no":"2021011515432900001","total_amount":"0.01","trade_no":"2021011522001498171441798181","seller_id":"2088911950619548"},"sign":"ls0PtRmswdvkFCCo2NOwLbe+93TKbRfR/K6O+RftocHrl0sSvZx2x7ESIRQSP5d1sINZMqNcRpMEUx85IZZCE+ISVdfISoR9jHiwxl2npHH/vEYBU7DQ5M9+jFZJqxq6Knn5nZChBkFGvw+TddhyW4jiSkvHc99atpLcRZsuYOr9YwzKK2PhLuOCqHiduGbaI9YyCUBUNhuhgQB9tvdBptfql3HKR0X0EVp2ChtKSruoD89bUFgDsXP0ei5SCwQ5LhvKM17vgILNdwgDElQ==","sign_type":"RSA2"}","resultStatus":"9000","memo":""}
  • 1

很明显字符串中的字符\\也被去除了,导致H5端JSON.parse无法解析json串

2、解决方案

iOS原代码如下

    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:resultDic options:0 error:&parseError];
    NSString *dataStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *resultDataStr =[NSString stringWithFormat:@"iOSPaycallback('%@')", dataStr];
    [_wkWebView evaluateJavaScript:resultDataStr completionHandler:nil];
  • 1
  • 2
  • 3
  • 4
  • 5

此时H5段接受用的如下方法

 var datares = JSON.parse(result);
  • 1

如果串中没有\\上面方法是正常的

改成如下

    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:resultDic options:0 error:&parseError];
    NSString *dataStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *resultDataStr =[NSString stringWithFormat:@"iOSPaycallback(%@)", dataStr];
    [_wkWebView evaluateJavaScript:resultDataStr completionHandler:nil];
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

此时H5段接受用的如下方法,不用JSON解析可以直接取值如result.resultStatus

 var datares = result;
  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/460696
推荐阅读
相关标签
  

闽ICP备14008679号