2017-11-28 9 views
0

RiotGames API를 사용하려고합니다. 나는 JSON 데이터를하고 난 C#을 수업이 JSON을 역 직렬화 할 필요가 있지만 오류 얻을 :리그 오브 레전드 API에서 JSON을 비 직렬화 할 때 오류가 발생했습니다.

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WFALeagueOfLegendsAPI.Heroes]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'datas.Aatrox', line 1, position 85.'

내 클래스 :

public class JsonRoot 
    { 
     public string type { get; set; } 
     public string format { get; set; } 
     public string version { get; set; } 
     public List<Heroes> datas { get; set; } 
    } 

    public class Heroes 
    { 
     public HeroesData Name { get; set; } 
    } 

    public class HeroesData 
    { 
     public string version { get; set; } 
     public string id { get; set; } 
     public string key { get; set; } 
     public string name { get; set; } 
     public string title { get; set; } 
     public HeroImage image { get; set; } 
    } 

    public class HeroImage 
    { 
     public string full { get; set; } 
     public string sprite { get; set; } 
     public string group { get; set; } 

     public override string ToString() 
     { 
      return full; 
     } 
    } 

C# 코드 :

var json = new WebClient().DownloadString("http://ddragon.leagueoflegends.com/cdn/6.24.1/data/en_US/champion.json"); 

json = json.Replace("data", "datas"); 
JsonRoot jr = JsonConvert.DeserializeObject<JsonRoot>(json); // this line has the error 
+0

보통 Newtsoft 쉬운 해킹 그냥 속성은'datas''하지 data' 이름 배열 –

+2

에 영웅 목록을 변경하면 배열이 잘 나열하지만 핸들. 속성의 이름을 변경하거나'JsonPropertyAttribute'를 사용하십시오 :'[JsonProperty (PropertyName = "data")]'. 데이터를 다시 포맷하기 위해'Replace '를 사용하지 마십시오. –

+0

@SaniSinghHuttunen 나는 당신의 충고를 시도하지만 같은 오류. 만약 내가 데이터 오류에 대한 대체 사용하지만 null을 반환 :/ –

답변

2

당신은 점점을 이 오류는 dataList<Heroes>을 사용하고 있기 때문에이 속성은 JSON의 배열이 아니기 때문에이 오류가 발생합니다. 대신 Dictionary<string, HeroesData>을 사용해야합니다. 영웅의 이름은 사전의 열쇠가 될 것입니다. 또한 JSON에있는 것보다 클래스의 특정 속성에 다른 이름을 사용하려면 아래와 같이 [JsonProperty] 속성을 사용할 수 있습니다. string.Replace을 사용하여 수업에 맞게 JSON을 변경하는 것은 좋지 않습니다. 의도하지 않은 작업을 대체 할 수 있기 때문입니다.

public class JsonRoot 
{ 
    public string type { get; set; } 
    public string format { get; set; } 
    public string version { get; set; } 
    [JsonProperty("data")] 
    public Dictionary<string, HeroesData> heroes { get; set; } 
} 

바이올린 : https://dotnetfiddle.net/kuKSrk