【问题标题】:How to remove first and last { } in a NSString in iOS?如何在 iOS 的 NSString 中删除第一个和最后一个 {}?
【发布时间】:2015-11-30 14:32:31
【问题描述】:

我想从我的 NSString 中删除第一个和最后一个括号。

{
    "Questions" : [
        {
          "title" : "This is my Question",
          "question_id" : "123123123213",
          "answers" : [
            "correct answer 1",
            "wrong answer 1",
            "wrong answer 2",
            "wrong answer 3"
          ],
          "media_type" : "",
        },
    {
          "title" : "This is my Question",
          "question_id" : "2342342342342",
          "answers" : [
            "correct answer 1",
            "wrong answer 1",
            "wrong answer 2",
            "wrong answer 3"
          ],
          "media_type" : "",
        }
      ]
    }

我只想从上面的NSString 中删除第一个和最后一个{ }

确保不是Dictionary。我在NSString 有这个。

【问题讨论】:

  • {} 总是字符串中的第一个和最后一个字符吗?
  • 这是你的 Json 字符串/数组兄弟,serlize 这个字符串你可以获得你的价值
  • 有几种方法可以解决这个问题。如果它们始终是字符串的第一个和最后一个字符,只需替换 @jipr311 链接中索引中的第一个和最后一个字符。或者你可以得到数组的第一个对象......或者得到“问题”键的 valueForKey
  • 看起来你有完美的 JSON(你可能是从 NSData 转换的,这完全没有必要),现在你想将它转换为一些损坏的 JSON。接下来你告诉我们你将手动解析它......在浪费大量时间之前查找 NSJSONSerialization。

标签: ios objective-c nsstring


【解决方案1】:

更新

选项正在序列化:

NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

NSDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:data
                                                     options:kNilOptions
                                                       error:nil];

NSArray *arr = dictJson[@"Questions"];

for (NSDictionary *dict in arr)
{ 
    NSLog(@"title ==%@",dict[@"title"]);
    .....
}

更新 2

但要小心你的字符串。这是错的。您必须检查 media_type 后的逗号:

{
"Questions" : [
    {
      "title" : "This is my Question",
      "question_id" : "123123123213",
      "answers" : [
        "correct answer 1",
        "wrong answer 1",
        "wrong answer 2",
        "wrong answer 3"
      ],
      "media_type" : ""**,** //THIS
    },
{
      "title" : "This is my Question",
      "question_id" : "2342342342342",
      "answers" : [
        "correct answer 1",
        "wrong answer 1",
        "wrong answer 2",
        "wrong answer 3"
      ],
      "media_type" : ""**,** //AND THIS
    }
  ]
}

没有逗号必须去那里。

【讨论】:

  • 第二个选项是正确的,去掉第一个选项——这是错误的兄弟..\
  • 好的,我要走了;)。那是一个快速的答案:)
  • 此代码不适用于问题中显示的字符串,因为该字符串不是有效的 JSON 数组。
  • 确实如此。 JSON 字符串上的错误是 "media_type" : "" 之后的逗号 ','。我要警告他
  • @nigelman 不,你误会了。 JSON 不是数组,而是字典。您的代码假定 JSON 是一个数组。 JSON 是带有“问题”键的字典。该键的值是字典数组。您需要修复答案中的代码。
猜你喜欢
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
相关资源
最近更新 更多