2017-01-29 3 views
-1

JSON에서 게임 값을 얻으려고하고 있지만 같은 이름의 필드가 여러 개 있기 때문에 그 개별 값을 검색 할 수있는 방법이 있는지 궁금합니다. 여기에 기본 JSON 구조입니다 :JObject를 사용하여 JSON에서 데이터 가져 오기

"response": { 

    "game_count": 119, 
    "games": [ 
     { 
      "appid": 3920, 
      "playtime_forever": 0 
     }, 
     { 
      "appid": 4000, 
      "playtime_forever": 278 
     }, 

...

내가 어떻게 든 playtime_forever 키를 검색 한 다음 APPID를 사용하여 속성을 얻을 필요가있다.

답변

3

당신은 클래스 다음 쿼리에 JSON을 변환 할 수 있습니다

class ResponseJSON 
{ 
    [JsonProperty("response")] 
    public Result Response { get; set; } 
} 

class Result 
{ 
    [JsonProperty("game_count")] 
    public string Count { get; set; } 
    [JsonProperty("games")] 
    public List<Game> Gmaes { get; set; }  
} 

class Game 
{ 
    [JsonProperty("appid")] 
    public string Id { get; set; } 
    [JsonProperty("playtime_forever")] 
    public string PlayTime { get; set; } 
} 

var resp = JsonConvert.DeserializeObject<ResponseJSON>(jsonstr); 

그리고 당신은 for 루프를 사용하여 객체를 통해 반복 할 수

foreach(game in resp.Respone.Games) { 
    var playtime = game.PlayTime; 
    // do stuff here 
} 

또는 당신은 쿼리 LINQ를 사용할 수 있습니다 게임 : 당신은 당신의 프로젝트의 경우에 here에서 newtonsoft DLL을 추가 할 필요가

var selectiveGames = resp.Response.Games.Where(x=> x.PlayTime == 220).ToList(); 

너는 그것을 가지고 있지 않다.

업데이트 : 원본 JSON을 사용하면 위의 코드가 완벽하게 작동합니다.

+0

foreach 루프에서 "객체 참조가 객체의 인스턴스로 설정되지 않았습니다"라고 표시했습니다. – John

+0

업데이트 확인 @John 방금 콘솔 앱으로 JSON을 테스트했는데 작동 중입니다 – Yaser

+0

거의 거기에''응답에 오류가 있습니다. 응답. 게임. 어디에서'':''CommandRegistry.Result에는 게임에 대한 정의가 없습니다 .'' – John

관련 문제