【问题标题】:NSString to JSON stringNSString 转 JSON 字符串
【发布时间】:2012-10-30 12:56:55
【问题描述】:

我有一个格式如下的NSString。目前它不是有效的 JSON 字符串。我想将其更改为 JSON 字符串并将其存储在 NSArray 中。 这是我的NSString.

[, {"Agent":" Visitor", "Time":"03:18 AM", "Message":"Msg from : file:///Users/satheesanop/Desktop/something.htmlIP Address : 182.72.139.142Country : IndiaCity : MadrasRegionName : Tamil N?duBrowser : Chrome 22OS : Mac", }, {"Agent":" agent name", "Time":"03:21 AM", "Message":"Thank you for contacting us.How may i help you ?", }, {"Agent":" Visitor", "Time":"03:22 AM", "Message":"Some message.", }]

感谢任何帮助。

【问题讨论】:

  • 如果可能,您应该修复服务器以向您提供有效的 JSON 字符串,因为解析 this 不会很有趣。
  • 有效的 json 格式为 : [ { "Agent": " Visitor", "Time": "03:18 AM", "Message": "Msg from : file:///Users/satheesanop /Desktop/something.htmlIP 地址 : 182.72.139.142国家 : IndiaCity : MadrasRegionName : Tamil N?duBrowser : Chrome 22OS : Mac" }, { "Agent": "agent name", "Time": "03:21 AM", “消息”:“感谢您与我们联系。有什么可以帮助您的吗?” }, {“代理”:“访客”,“时间”:“03:22 AM”,“消息”:“一些消息。” } ]

标签: ios json cocoa-touch nsstring


【解决方案1】:

您需要使用dataUsingEncoding: 方法将NSString 转换为NSData

然后使用JSONObjectWithData 方法并将其添加到数组中。

NSArray *arrayJson = [NSArray arrayWithObjects:[NSJSONSerialization JSONObjectWithData:data options:0 error:nil],nil];

【讨论】:

    【解决方案2】:

    想通了..

    Mystr = [Mystr stringByReplacingOccurrencesOfString:@"[,"  withString:@"["];
    Mystr = [Mystr stringByReplacingOccurrencesOfString:@", }" withString:@"}"];
    

    谢谢大家。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-28
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 2013-12-12
      • 2015-12-11
      • 1970-01-01
      相关资源
      最近更新 更多