【问题标题】:How to get array of json value using Graphql in swift 4?如何在 swift 4 中使用 Graphql 获取 json 值数组?
【发布时间】:2019-02-19 22:08:31
【问题描述】:

我正在使用 graphql 通过 Apollo 获取 API 值。我已成功下载 schema.json 并从 grpahql 获取值。但我无法获取 json 值的 values 数组。

这是我的示例回复:

 {
  "data": {
  "team_Dashboard": {
  "activeMission": "Food Mission",
  "currentMissionChallenges": [
   {
    "id": "123",
    "title": "Challenge",
    "estTime": "5",
    "location": "Anywhere",
    "maxPts": "30",
    "status": "Not yet started"
   },
   {
    "id": "1234",
    "title": " II Challenge",
    "estTime": "5",
    "location": "Anywhere",
    "maxPts": "70",
    "status": "Not yet started"
    }
   ]
  }
 }
}

Graphql 查询:

query teamDashboard($teamId: ID!) {
  team_Dashboard(teamId: $teamId) {
   activeMission
   currentMissionChallenges
 }
}

Graphql 架构响应:

missionDeadLine: String
currentMissionChallenges: [JSON]

当我在我的 Graphql 查询中添加 currentMissionChallenges([JSON]) 时,会从服务器获取错误响应。但是当我从 Graphql 查询中删除 currentMissionChallenges 时,会从服务器获取成功响应和值。

问题是 currentMissionChallenges 是 [JSON] 格式。当我更改我的 graphql 查询 This is graphql Response

 query teamDashboard($teamId: ID!) {
  team_Dashboard(teamId: $teamId) {
   activeMission
   currentMissionChallenges {
        id
        title
        estTime
        location
        maxPts
        status
    }
  }
}

dashBord.grpahql 中显示以下错误

Field "currentMissionChallenges" must not have a selection since type "[JSON]" has no subfields.

如何从 graphql 获取 json 数组值。获取 Json 值有什么问题?请帮帮我!

【问题讨论】:

    标签: json swift graphql apollo


    【解决方案1】:

    The best thing about GraphQL is we can use the query as model

    因为响应与查询相同,所以我们可以将响应分配给查询类型的变量。

    让我用一个例子来解释:-

    假设如果我需要查询我的个人资料数据,

    Profile.graphql

    query MyProfile{
        player {
            me {
                id
                secret
                name
                email
                state
                country
                timezone
                picture
                pictureType
                audio
                rank
            }
        }
        countries{
            value
            viewValue
        }
    }
    

    一旦我们构建了应用程序,它就会在 API.swift 中创建 MyProfileQuery。在 viewController 中,我们可以使用如下响应 -

    var myProfileData: MyProfileQuery.Data.Player.Me? // Declaring the valiable of player Type
    
    ApolloClientManager.sharedInstance
                    .fetchQuery(MyProfileQuery(), showLoader: true,
                                viewController: self) { (response) in // Fetching response using Apollo Client Manager
                    if let allData = response {
                        if let profiledata = allData.player?.me {
                            self.myProfileData = profiledata // Assigning response into the variable declared
                            self.myEdittingProfileData = profiledata
                            self.updateUI()
                        }
                        if let countryData = allData.countries {
                            self.allCountrydata = countryData
                            self.getPickerDataForState(comppletion: {
                                self.openTimeZonePicker(completion: {
                                    print("got timeZone Data")
                                })
                            })
                        }
                    }
    
                }
    

    现在我们可以使用对 myProfileData 变量的响应 如下-

    现在我们可以访问我们在查询中提到的所有值,如下所示

    print("player id is-          \(myProfileData?.id)")
    print("player name is-        \(myProfileData?.name)")
    print("player email is-       \(myProfileData?.email)")
    print("player state is-       \(myProfileData?.state)")
    print("player rank is-        \(myProfileData?.rank)")
    print("player pictureType is- \(myProfileData?.pictureType)")
    
    // player id is-          10
    // player name is-        jordan
    // player email is-       jordan@domain.com
    // player state is-       Ohio
    // player rank is-        101
    // player pictureType is- custome
    // 
    

    希望对你有所帮助???

    【讨论】:

      【解决方案2】:

      我建议你使用自定义标量。

      import Apollo
      public typealias JSON = [String: Any]
      
      extension Dictionary: JSONDecodable {
      public init(jsonValue value: JSONValue) throws {
      
          if let array = value as? NSArray {
              self.init()
              if var dict = self as? [String: JSONDecodable & JSONEncodable] {
                  dict["data"] = array as! [[String: Any]]
                  self = dict as! Dictionary<Key, Value>
                  return
              }
          }
      
          guard let dictionary = value as? Dictionary else {
      
              throw JSONDecodingError.couldNotConvert(value: value, to: Dictionary.self)
          }
          self = dictionary
      }
      

      }

      var currentMissionChallanges = [JSON]()
      func getTeamDashboard(id:String) {
           let query = TeamDashboardQuery(id:id)
           apollo.fetch(query:query) { [weak self] result, error in 
                if let dashboards = result.data?.team_dashboard {
                   if let array = dashboards!["currentMissionChallanges"] as? 
      [JSON] {
      self?.currentMissionChallanges = array
      }
                }
           }
      }
      

      【讨论】:

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