【问题标题】:iOS JSON Parsing, Format IssuesiOS JSON 解析,格式问题
【发布时间】:2015-11-01 20:52:46
【问题描述】:

所以我正在做一个需要我使用一些 JSON 的项目,我遇到了一些关于表示事物的最佳方式的问题。首先,这是 JSON 的外观:

"phoneList": [
  {
    "phoneReason": "End of Contract",
    "phoneType": [
      {
        "id": 5,
        "phoneType": "Android Smartphone"
      }
     ]
    }
   ]

我想知道最合适的表达方式。

例如,我知道我的 phoneReason 只是一个简单的 NSString,而我的 phoneType 实际上是一个 NSArray。但是,我不知道如何表示 a) id,我知道这是一个整数,但它应该是 NSInteger 还是 NSNumber 并且 b) 有人可以指出我可以理解的一些示例代码的方向对包含整数和字符串的字典对象进行建模,并且我可以在其中了解如何对字典数组进行建模。

我的另一个问题也类似,说我实际上正在发布一些东西,我如何对此建模,特别是对于包含数字/整数和字符串的字典类型(JSON 花括号)对象。

例如,这是我尝试建模的 JSON,然后执行以下操作:

"phoneReason": "Upgrade",
"phoneInfo": {
  "id": "2"
},

//然后我要传ID

-(void) createOurRequest:(NSNumber *)id {

NSDictionary *myDictionary = @{
        @"phoneReason" : [NSString stringWithFormat:@"%i",   s  elf.dat.reason],
      //How do I then represent the phoneInfo element exactly?
};

抱歉,对于这个笨拙的问题,非常感谢任何有关在 iOS 中或一般情况下建模 JSON 的指导。

【问题讨论】:

    标签: ios objective-c json nsarray nsdictionary


    【解决方案1】:

    我假设您在问问题 a) 和 b),以及如何建模 JSON。

    a) Obj-C 的不幸之处在于所有集合元素都必须是对象。整数是值类型,因此需要将它们转换为 NSNumbers 才能工作。但是,如果您要解析 JSON 字符串,内置的 JSON 解析器会为您完成。我会在下面描述它。

    b) 该模型基于 JSON。 您描述对象集合,解析器将为您确定模型。在您的示例中,您将有一个NSDictionary<NSString *: NSArray<NSDictionary<NSString *: id>*>*>。最里面的元素的值为id,因为您可以拥有NSString ("End of Contract") 或NSArray ("phoneType": [ { "id": 5, "phoneType": "Android Smartphone" } ])

    当然,模型是由您的 JSON 定义的,因此如果您通过解析器运行它,您会得到一个结构化对象。您可以根据您的模型访问每个元素 (object[@"phoneList"][@"phoneReason"])。

    要使用的类方法是:

    + (id)JSONObjectWithData:(NSData *)data
                     options:(NSJSONReadingOptions)opt
                       error:(NSError **)error
    

    你传递一个NSData 表示你的字符串、选项(或0)和一个NSError 指针(error*)。你会得到一个你定义的正确结构的解析 JSON。

    NSDictionary *parsedJSONObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:NULL
    

    我没有可用的选项,而且我知道不会有错误,所以我没有为这些参数传递任何内容。生成的对象将采用您的 JSON 的任何结构。

    【讨论】:

      【解决方案2】:

      使用您在第一个示例中提供的对象和 json 布局,这就是我将如何创建字典和数组以获取您指定格式的 json。希望这有助于让您更清楚一点。

      // example constructor method
      -(void) jsonStringWithPhoneReason:(NSString*)reason phoneId:(NSInteger)phoneId phoneType:(NSString*)phoneType
      {
          // create device detail dictionary
          NSDictionary *deviceOneDetail = @{
                                            @"id" : @(phoneId),       // <- set phone id as NSNumber
                                            @"phoneType" : phoneType  // <- set your string phone type
                                            };
      
          // create device dictionary
          NSDictionary *deviceOne       = @{
                                            @"phoneReason" : reason,          // <- set your phone reason string
                                            @"phoneType" : @[deviceOneDetail] // <- set your phone type dictionary within an array
                                            };
      
          // create phone list dictionary with any device dictionaries you want to add
          NSDictionary *phoneListDict   = @{
                                            @"phoneList" : @[
                                                              deviceOne,      // <- add your device to the phone list array of dictionaries
                                                              // deviceTwo...
                                                              ]
                                            };
      
          NSString *jsonString = [self convertToJsonString:phoneListDict];    // <- convert the dictionary into a json string and use however you wish
      
          // your json string should now look like this assuming you pass 'End of Contract', 5 & 'Android Smartphone' as arguments to this method
          // {"phoneList":[{"phoneReason":"End of Contract","phoneType":[{"id":5,"phoneType":"Android Smartphone"}]}]}
      }
      
      
      
      -(NSString*) convertToJsonString:(NSDictionary*)dictionary
      {
          NSError *error;
      
          NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                             options:0 // Pass 0 if you don't care about the readability of the generated string
                                                               error:&error];
      
          if (error)
          {
              NSString *errorDesc = [NSString stringWithFormat:@"Error creating json data from dictionary: %@", error.localizedDescription];
              NSLog(@"ERROR: %@", errorDesc);
              jsonData = nil;
              return nil;
          }
      
          NSString *returnString = nil;
      
          if(jsonData != nil)
          {
              returnString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
          }
      
          return returnString;
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多