【问题标题】:Get dataset from JSON by parameter通过参数从 JSON 中获取数据集
【发布时间】:2020-12-09 09:16:46
【问题描述】:

尝试使用我的参数从 JSON 中查找唯一数据集。

我有 JSON“userDetails”:

{
"userDetails": [
                {
                "name": "Sabine",
                "imageUrl" :"https://randomuser.me/api/portraits/men/82.jpg",
                "content": [
                            {
                            "type": "video",
                            "url": "https://storage.googleapis.com/coverr-main/mp4/Travaho.mp4"
                            },
                            {
                            "type": "image",
                            "url": "https://picsum.photos/640/1136/?image=281"
                            }
                            ]
                },
                {"name": "Keila Maney",
                "imageUrl" :"https://randomuser.me/api/portraits/women/81.jpg",
                "content": [
                            {
                            "type": "image",
                            "url": "https://picsum.photos/640/1136/?image=273"
                            },
                            {
                            "type": "video",
                            "url": "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
                            }
                            ]
                }
                ]

}

我知道我的用户是 Keila Maney(我的代码中有用户属性)并且需要将该参数发送到 JSON,并且只接收返回 Keila Maney strong> 属性(就是imageUrl, content(type, url))然后解析。

有没有标准的 JSON 搜索方法?

提前致谢!

【问题讨论】:

  • need to send that parameter to JSON 是什么意思?
  • 没有标准。这取决于后端
  • 这意味着在JSON中我有很多记录,我需要用我的参数过滤掉它们(在我的例子中参数是“name”="Keila Maney")

标签: ios json swift parsing search


【解决方案1】:

Json 示例:

{  
  "places": [  
    {  
      "name": "Ulrikh",
      "id": 555,
    },  
    {  
      "name": "Place 2",  
      "id": 1,  
    }
]  
} 

呼叫:

 self.getDataByID(id: 555)

Swift 方法:

func getDataByID(id : Int) {
        let data = self.getData()
        
        
            for i in 0..<data.count
            {
            if(Int((((data as NSDictionary)["places"] as! NSArray)[i] as! NSDictionary)["id"] as! Int) == id)
            {
                print("here is result:")
                print((((data as NSDictionary)["places"] as! NSArray)[i]))
            }
        }
    }
    
    func getData() -> NSDictionary {
        do{
            let path = Bundle.main.path(forResource: "test", ofType: "json")
            let jsonData = NSData(contentsOfFile: path!)
            let jsonResult:NSDictionary!  = try JSONSerialization.jsonObject(with: jsonData! as Data , options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
            return jsonResult
        } catch let error as NSError {
            print(error)
        }
        
        return NSDictionary()
    }

不用谢:)

【讨论】:

    【解决方案2】:

    只需创建 UserDetails 对象,例如:var userData: [UserDetails]? 并在循环中检查userData[x].name == "Keila Maney"。那么这个 x 将成为 Keila Maney 的索引,您可以获取它的所有数据。将您的 json 数据绑定到 UserModel 对象后。这些是您将从 json 创建的三个类

    1. 用户模型

      struct UserModel : Codable {
      let userDetails : [UserDetails]?
      
      enum CodingKeys: String, CodingKey {
      
           case userDetails = "userDetails"
      }
      
      init(from decoder: Decoder) throws {
         let values = try decoder.container(keyedBy: CodingKeys.self)
         userDetails = try values.decodeIfPresent([UserDetails].self, forKey:.userDetails)
      }
      
      }
      
    2. 用户详情

      struct UserDetails : Codable {
      let name : String?
      let imageUrl : String?
      let content : [Content]?
      
      enum CodingKeys: String, CodingKey {
      
          case name = "name"
          case imageUrl = "imageUrl"
          case content = "content"
      }
      
      init(from decoder: Decoder) throws {
          let values = try decoder.container(keyedBy: CodingKeys.self)
          name = try values.decodeIfPresent(String.self, forKey: .name)
          imageUrl = try values.decodeIfPresent(String.self, forKey: .imageUrl)
          content = try values.decodeIfPresent([Content].self, forKey: .content)
      }
      
      }
      
    3. 内容

      struct Content : Codable {
      let type : String?
      let url : String?
      
      enum CodingKeys: String, CodingKey {
      
          case type = "type"
          case url = "url"
      }
      
      init(from decoder: Decoder) throws {
          let values = try decoder.container(keyedBy: CodingKeys.self)
          type = try values.decodeIfPresent(String.self, forKey: .type)
          url = try values.decodeIfPresent(String.self, forKey: .url)
      }
      
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-07
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多