2013-09-21 5 views
0

답변은 매우 간단하지만 문제가 있습니다. JSON.NET JToken에서 내 모델 객체를 구문 분석하려고하는데 다음 JSON 문자열 (Yahoo Fantasy Sports API에서 제공)이 있습니다. JSON 구문 분석을 지원하기 위해 특별히 프로젝트를 정리하고 싶지 않기 때문에 수동으로이 작업을 수행하려고합니다. 그러나, 나는 내 인생이 코드에서 설정 케이스에 있는지 또는 팀 케이스에 있는지를 결정할 수 없다. 도움? 내가 그렇게 리그에서/개 이상의 서로 다른 하위 자원을로드 할 수 있기 때문에 그것을 하드 코드하지 않으JSON.NET JArray 요소를 구별하는 방법

public League ParseJson(JToken token) 
{ 
    var league = new League(); 
    if (token.Type == JTokenType.Array) 
    { 
     foreach (var child in token.Children<JObject>()) 
     { 
      // how do I figure out if this child contains the settings or the teams? 
     } 
     return league; 
    } 
    return null; 
} 

:

{ 
    "league":[ 
     { 
     "league_key":"somevalue", 
     "name":"My League" 
     }, 
     { 
     "teams":{ 
      "0":{ 
       "team":[ 
        [ 
        // some data 
        ] 
       ] 
      }, 
      "1":{ 
       "team":[ 
        [ 
        // some data 
        ] 
       ] 
      }, 
      "count":2 
     } 
     } 
    ] 
} 

다음 (지금까지) 구문 분석 내가 사용하는 코드입니다 항상이 구조체를 포함한다는 보장은 없습니다.

답변

1

자식 개체가 원하는 하위 리소스의 알려진 속성 (다른 하위 리소스에도 포함되어 있지 않음)을 포함하는지 여부를 확인하기 만하면됩니다. 이런 식으로하면 효과가 있습니다. 나머지는 채울 수 있습니다.

public League ParseJson(JToken token) 
{ 
    var league = new League(); 
    if (token.Type == JTokenType.Array) 
    { 
     foreach (JObject child in token.Children<JObject>()) 
     { 
      if (child["teams"] != null) 
      { 
       // process teams... 
       foreach (JProperty prop in child["teams"].Value<JObject>().Properties()) 
       { 
        int index; 
        if (int.TryParse(prop.Name, out index)) 
        { 
         Team team = new Team(); 
         JToken teamData = prop.Value; 

         // (get team data from JToken here and put in team object) 

         league.Teams.Add(team); 
        } 
       } 
      } 
      else if (child["league_key"] != null) 
      { 
       league.Key = child["league_key"].Value<string>(); 
       league.Name = child["name"].Value<string>(); 
       // (add other metadata to league object here) 
      } 
     } 
     return league; 
    } 
    return null; 
} 

class League 
{ 
    public League() 
    { 
     Teams = new List<Team>(); 
    } 

    public string Key { get; set; } 
    public string Name { get; set; } 
    public List<Team> Teams { get; set; } 
} 

class Team 
{ 
    // ... 
} 
+0

스위트. 디버깅 및 존재하지 않는 인덱스를 사용하여 배열 인덱싱을 사용하는 동안 예외가 발생하여 null을 확인하지 않은 것으로 나타났습니다. 그러나 컴파일 된 코드에서는 그렇게하지 않으므로이 방법이 효과적입니다. – sohum