2017-02-07 77 views
3

我試圖消耗它返回一個JSON建成一個API播放:與類型提供和JSON API

Team.player1/player2/player3 ...(球員都建成性質,而不是作爲一個數組)

我正在考慮用反射來做到這一點,但很難找到一個球員。

type Simple = JsonProvider<"sample.json"> 

let wbReq = "API-FOR-TEAM"  

let docAsync = Simple.Load(wbReq) 

let allValues = FSharpType.GetRecordFields (docAsync.Team.Players.GetType()) 
let test = allValues 
      |> Seq.map (fun p -> (p.GetValue(docAsync.Team.Players) as ?).Name) // HOW TO GET THE TYPED PLAYER HERE ? 
      |> fun p -> printfn p 

編輯:我試圖用gettype和System.Convert.ChangeType

EDIT2:這裏是JSON的一個簡化版本:

{ 
    "Team": { 
     "id": "8", 
     "players": { 
      "17878": { 
       "info": { 
        "idteam": 8, 
        "idplayer": 17878, 
        "note": 6 
       } 
      }, 
      "18507": { 
       "info": { 
        "idteam": 8, 
        "idplayer": 18507, 
        "note": 5 
       } 
      } 
     } 
    } 
} 

編輯3:

我在C#中找到了一個簡單的解決方案(感謝JSON.net和動態),但爲了學習的目的,我想在F#中做同樣的事情,如果有人想要幫助:

 private static List<Player> Parse(string jsonString) 
     { 
      dynamic jsonObject = JsonConvert.DeserializeObject(jsonString); 

      var players = ParseItems(jsonObject.Home.players); 

      return players; 
     } 

     private static List<Player> ParseItems(dynamic items) 
     { 
      List<Player> itemList = new List<Player>(); 
      foreach (var item in items) 
      { 
       itemList.Add(new Player() 
       { 
        idplayer = item.Value.info.idplayer, 
        lastName = item.Value.info.lastname, 
        note = item.Value.info.note 
       }); 
      } 
      return itemList; 
     } 
+0

不知道我明白你想得到什麼 –

+1

也許你可以展示json的例子嗎? –

+0

肯定@FoggyFinder讓我知道現在是否更好,thx – rad

回答

2

你可以混合使用JsonTypeProvider和解析Json。例如:

[<Literal>] 
let sample = """{ 
    "Team": { 
     "id": "8", 
     "players": { 
      "17878": { 
       "info": { 
        "idteam": 8, 
        "idplayer": 17878, 
        "note": 6 
       } 
      }, 
      "18507": { 
       "info": { 
        "idteam": 8, 
        "idplayer": 18507, 
        "note": 5 
       } 
      } 
     } 
    } 
}""" 

type Player = {IdTeam:int; IdPlayer:int; Note:int} 

type Simple = JsonProvider<sample> 
let docAsync = Simple.GetSample() 

let json = docAsync.Team.Players.JsonValue 

let parseInfo (json:JsonValue) = 

    let id_team = (json.GetProperty "idteam").AsInteger() 
    let id_player = (json.GetProperty "idplayer").AsInteger() 
    let note = (json.GetProperty "note").AsInteger() 

    {IdTeam = id_team; IdPlayer = id_player; Note = note} 

let players = 
    json.Properties() 
    |> Array.map(fun (_,x) -> x.GetProperty "info") 
    |> Array.map (parseInfo) 

players 
|> Array.iter (printfn "%A")