【问题标题】:How do I use this JSON text in my app?如何在我的应用程序中使用此 JSON 文本?
【发布时间】:2015-01-05 04:36:06
【问题描述】:

我有以下 JSON 文本,如下所示。我想将它合并到我的应用程序中,并且能够将它的一部分分配给要使用的变量。很简单,我知道,但我不知道该怎么做。

[{"id":"1","category":"1","fact":"Worldwide, around 1.2 trillion eggs are produced for eating every year, which means that average person on Earth consumes 173 eggs a year."},{"id":"3","category":"2","fact":"How to tell if you're going to throw up? -Your mouth starts to fill with saliva which is there to protect your mouth and teeth from the stomach acid mixed with the vomit."},{"id":"2","category":"2","fact":"Bone cells are constantly renew so every ten years you have a new skeleton."}] 

【问题讨论】:

  • NSJSONSerialization上做一些搜索。
  • 请注意,如果您在 Google 上搜索“objective-c json”,您会得到几十个示例。

标签: objective-c json


【解决方案1】:

您的文本看起来像一个数组。所以试试这样:-

NSError *err = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &err];

【讨论】:

    【解决方案2】:

    如果您的 json 文本是 NSString,则需要将其转换为 NSData:

        NSString* jsonText = @"[{"id":"1","category":"1","fact":"Worldwide, around 1.2 trillion eggs are produced for eating every year, which means that average person on Earth consumes 173 eggs a year."},{"id":"3","category":"2","fact":"How to tell if you're going to throw up? -Your mouth starts to fill with saliva which is there to protect your mouth and teeth from the stomach acid mixed with the vomit."},{"id":"2","category":"2","fact":"Bone cells are constantly renew so every ten years you have a new skeleton."}]";
        NSData* data = [jsonText dataUsingEncoding:NSUTF8StringEncoding];
    
        NSError* error;
        NSDictionary* jsonDict = [NSJSONSerialization 
        JSONObjectWithData:responseData
        options:kNilOptions 
        error:&error];
    

    所以现在您可以像字典一样访问元素。 希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-10-09
      • 2021-10-05
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      • 1970-01-01
      • 2016-11-16
      相关资源
      最近更新 更多