【问题标题】:NSDictionary to JSON with NSJSONSerialization issueNSDictionary 到 JSON 与 NSJSONSerialization 问题
【发布时间】:2014-07-14 23:34:55
【问题描述】:

我有一个NSDictionary(参数),其中包含以下数据:

{
    deviceType = iPhone;
    ordersActionList = ({
            endDate = "07/14/2014 14:32";
            orderId = 2807171;
            reason = "Some reason";
        }
    );
}

当我使用NSJSONSerialization 解析上述内容时:

NSError *err;
NSData *jsonData =[NSJSONSerialization dataWithJSONObject:params options:0 error:&err]; 

endDate 中添加转义字符,endDate 显示如下:

 `"endDate": "07\/14\/2014 14:32"`

这是不正确的,有人可以建议我在使用 NSJSONSerialization 进行序列化时如何避免 JSON 中的转义字符吗?

编辑: 这是我目前的工作,但我不喜欢这样做,我希望有更好的解决方案:

-(NSData*) converToNSData:(NSDictionary *)params
{
    NSError * err;
    NSData *jsonData =[NSJSONSerialization dataWithJSONObject:params options:0 error:&err];

    NSString *jsonStr1 = [NSString stringWithUTF8String:[jsonData bytes]];
    jsonStr1 = [jsonStr1 stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];

    NSData *jsonData2 =[jsonStr1 dataUsingEncoding:NSUTF8StringEncoding];

    return jsonData2;
}

【问题讨论】:

  • 这正是它应该做的。
  • 黑斜线必须在 JSON 字符串中进行转义。
  • troop231,我已经有了解决方法的答案,但我忘了把它放在我的初始帖子中,但我最初不能使用这个解决方案,因为我不应该接触 json ......我正在寻找一种方法要通过 NSJSONSerialization 做到这一点,如果那是不可能的,那么我将不得不以不同的方式将日期发送到 JSON,不过感谢您的建议。
  • 你为什么要解决一个不存在的问题???
  • 热舔,我没听懂你。我认为应该有一种方法可以告诉 NSJSONSerialization 保持文本不变。

标签: ios nsdictionary nsjsonserialization


【解决方案1】:

如果您要避免在日期中使用转义的斜线,那么 NSJSONSerialization 就无法做到这一点。但是请注意,生成的 JSON 数据是完全有效的,如果您对其进行反序列化,您将获得原始数据。

如果您仍想删除反斜杠,则必须将结果转换为 NSString 并自己进行搜索/替换。

相关: how to prevent NSJSONSerialization from adding extra escapes in URL

【讨论】:

  • 感谢您的链接,但我已经阅读了这篇文章,我有一个解决方案,请检查我的编辑,但我希望有更好的解决方案。转换和替换有点繁琐。
  • 诚然,搜索/替换对于您想做的事情来说相当乏味,但它似乎是最好的方法。
【解决方案2】:

您可以这样做,但是如果您的数据有两个反斜杠,它们将被删除。如果您可以保证您的数据没有两个反斜杠,那就可以了。

NSString *newString = [[yourDict objectForKey:@"endDate"] 
stringByReplacingOccurrencesOfString:@"\\" withString:@""];

【讨论】:

    【解决方案3】:
       var returnString:String?
        do
        {
            let jsonData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted)
    
            if let json = String(data: jsonData, encoding: .utf8) {
                returnString=json.replacingOccurrences(of: "\\", with: "")
            }
    
        }
        catch {
            print("something went wrong with parsing json")
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-24
      • 1970-01-01
      相关资源
      最近更新 更多