【问题标题】:How to load JSON to array ios?如何将 JSON 加载到数组 ios?
【发布时间】:2017-05-16 06:02:50
【问题描述】:

我在线创建了 JSON,因为我必须将 JSON 插入到我在本地使用的数据库中。

所以到目前为止,我从网上创建了 JSON:

{
  "City": [
    "Anaheim",
    "Surat",
    "Aheldaba",
    "Vadobasa"
  ],
  "State": [
    "Gujarat",
    "Pennsylvania",
    "MP",
    "ULK"
      ],

  ",string": ",Hello World"
}

现在我必须把这个 JSON 放到我的数组中,这样我就可以轻松地将它添加到数据库中。

有什么办法可以直接把这个JSON加入哟数组?

【问题讨论】:

  • 始终显示您尝试过的代码
  • 我可以直接将此 JSON 复制到数组吗?
  • 是的,你可以直接使用它
  • @KaviPatel Json 数组不是字典?
  • 将其放入资源中的文件中,从该文件加载NSData 并使用NSJSONSerialization 解析该数据。

标签: ios objective-c iphone json


【解决方案1】:

试试看。

NSString *jsonString = @"your json string";
NSData *jSONObjectWithData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization jSONObjectWithData:jsonData options:kNilOptions error:&jsonError];

【讨论】:

    【解决方案2】:

    首先您需要通过执行以下操作将您的 json 字符串转换为 NSData

    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *parsingError = nil;
    
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parsingError];
    
    NSArray *cityArray = [json objectForKey:@"City"];
    

    【讨论】:

      【解决方案3】:
       if (data) {
                      NSError* error;
                      NSDictionary* json = [NSJSONSerialization
                                            JSONObjectWithData:data //1
                                            options:kNilOptions
                                            error:&error];
          if(!error){
      
          id totalRecords = json.mutableCopy;//[json objectForKey:@"hits"];
      
               if ([totalRecords isKindOfClass:[NSDictionary class]]) {
                          NSArray *records =[totalRecords objectForKey:@"data"];
      
                }
                else if ([totalRecords isKindOfClass:[NSArray class]]){
                          NSArray *records =totalRecords.mutableCopy;
      
                 }
      
          }
      }
      

      【讨论】:

        【解决方案4】:

        这就是你如何创建一种字典或者你说键值对的方法。但是,您绝对必须使用UTFStringEncoding 将子字符串转换为数据,然后将其提供给NSJSONSerialization.JSONObject() 以获得键值对。

        class JSON{
            func convertJSON(){
                do{
                    let data:NSData? = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
                    let json = try? NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
                    print(json)
                }
                catch {
                    print("Error is \(error)")
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-12-09
          • 2014-12-29
          • 2021-10-24
          • 2021-07-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多