2014-06-20 7 views
1

나는 다른 형태의 JSON 데이터 일반적으로 필터 JSON 정보

내가 모든 경우에 작동하고 동적 클래스를 사용하여 JSON을 구문 분석하는 (아니 내가 같은 항목이 있습니다받을 JSON 파일을 모두)를 수신하고 JSON 파일은 동일한 항목을 가지고 있지만이 경우에는 작동하지 않습니다. 다음 데이터에 대한 예를 들어

:

[ 
    { 
     "Player_Name": "Zlatan Ibrahimovic", 
     "Country": "Sweeden", 
    }, 
    { 
     "Player_Name": "Pavel Nedved", 
     "Country": "Czech Republic", 
     "Personal_Honours": 
     { 
      "Ballon_DOr": "One", 
     }, 
    } 
] 

처음 두 요소는 2 명 개의 제 1 엔트리를 공유 "PLAYER_NAME"와 "국제"그러나 두 번째 요소는 "Personal_Honours"

제 2 입력을 갖는다

나는이 할 그렇다면 :

:이 클래스

StreamReader reader = File.OpenText("TextFile1.txt"); 
List<PlayerData> DataList; 
dynamic json = JsonConvert 
    .DeserializeObject<dynamic>(reader.ReadToEnd()); 


DataList = new List<PlayerData>(); 
foreach (dynamic data in json) 
{ 
    DataList.Add(new PlayerData 
    { 
     Name = json.Player_Name, 
     Country = json.Country , 
     BallonDor = json.Personal_Honours.Ballon_DOr 
    }); 
} 

내가 얻을 RuntimeBinderException 첫 번째 항목은 Personal_Honours를 포함하지 않기 때문에 분석 할 JSON은

가 어떻게이 오류를 관리 할 수 ​​있습니다 이 항목을 포함 할 경우 "나는 미리 알 수 없습니다?

답변

0

당신은 물건을 혼합하고 있습니다.

deserilizer는 데이터를 저장하는 방법을 모르거나 신경 쓰지 않습니다. deserilize 할 문자열과 Deserilized 데이터를 사용하여 인스턴스를 만드는 Object 유형 만 가져옵니다.

두 번째 클래스와 첫 번째 클래스를 혼합합니다.

예를 들어, 나는 다음과 같이 그것을으로 나눔 것 : 물론

Player class: 
- Name (string) 
- Country (string) 
- PersonalHonours (class) 

PersonalHonours class 
- BallonDOr (string) 
- etc.. 

, 명명 많은 부분에서와 같이 다른 경우에 어디에 '_'다른, 당신이 그 그 deserilizer을 "에게"한다 실제로 해당 속성 [JsonProperty("Ballon_DOr")] 속성을 추가하여 다른 키와 바인딩합니다.

결국, 전체 문자열에 deserilizer를 사용하기 만하면 사용할 준비가됩니다.

1

당신이 JSON 객체에 대한 구체적인 클래스를 사용하지 않으려면, 당신은 익명 클래스의 힘을 사용할 수 있습니다

 var sample = new[] 
     { 
      new 
      { 
       Player_Name = "", 
       Country = "", 
       Personal_Honours = new 
       { 
        Ballon_DOr = "", 
       }, 
      } 
     }; 

사용 : 그냥이 같은 모든 가능한 속성을 사용하여 샘플 객체를 정의 그 .GetType()은 다음과 같이 JSON 디시리얼라이저에 전달할 :

internal class Program 
{ 
    public class PlayerData 
    { 
     public string Name { get; set; } 
     public string BallonDor { get; set; } 
     public string Country { get; set; } 
     public string MarketValue { get; set; } 
     public string CurrentClub { get; set; } 
    } 

    private static void Main(string[] args) 
    { 
     var sample = new[] 
     { 
      new 
      { 
       Player_Name = "", 
       Country = "", 
       Personal_Honours = new 
       { 
        Ballon_DOr = "", 
       }, 
      } 
     }; 

     dynamic json = JsonConvert.DeserializeObject(@"[ 
{ 
    ""Player_Name"": ""Zlatan Ibrahimovic"", 
    ""Country"": ""Sweeden"", 
}, 
{ 
""Player_Name"": ""Pavel Nedved"", 
""Country"": ""Czech Republic"", 
    ""Personal_Honours"": { 
    ""Ballon_DOr"": ""One"", 
}, 
} 
]", sample.GetType()); 

     var dataList = new List<PlayerData>(); 
     foreach (var data in json) 
     { 
      dataList.Add(
       new PlayerData 
       { 
        Name = data.Player_Name, 
        Country = data.Country, 
        BallonDor = data.Personal_Honours == null ? null : data.Personal_Honours.Ballon_DOr 
       }); 
     } 
    } 
} 
:

여기
 dynamic json = JsonConvert.DeserializeObject(myJsonString, sample.GetType()); 

이 당신의 소스를 기반으로 전체 작업 샘플입니다

+0

나는 Zlatan Ibrahimovic 항목에 "Market_Value"를 추가하기 위해 json 데이터를 편집했지만 다른 항목은 추가하지 않았습니다. "MarketValue = data.Market_Value == null? null : data.Market_Value "하지만 RuntimeBinder Excepetion에 무엇이 잘못 되었습니까? – user2505650

+0

@ user2505650'Ballon_DOr'은 루트 객체의 일부가 아니며'Personal_Honours' 클래스의 속성입니다. 따라서 PlayerData 클래스를 잊어 버리고 그것에 대해 조금. 내 질문을 다시 읽으십시오 (올바른 방법을 보여줍니다). 곧 제거 할 것이기 때문에. –