2016-12-11 8 views
0

Я немного новичок в сериализации/десериализации строк JSON. Я пытался использовать Newtonsoft.Json. Дело в том, что я получил строку JSON, полученную от url: http://epguides.frecar.no/show/gameofthrones/, и я хотел бы создать и объект класса из него. Поэтому позже я мог распечатать его ...JSON десериализация не десериализуется?

Я узнал, как создавать классы из вашей JSON строки, путем копирования строки и Edit> Paste_Special> Paste_JSON_as_Classes так что должно быть в порядке.

Создаваемые классы:

namespace TvSeries 
{ 

public class Show 
{ 
    public string title { get; set; } 
    public string imdb_id { get; set; } 
    public string epguide_name { get; set; } 
} 

public class __invalid_type__1 
{ 
    public Show show { get; set; } 
    public string title { get; set; } 
    public int number { get; set; } 
    public int season { get; set; } 
    public string release_date { get; set; } 
} 

public class Show2 
{ 
    public string title { get; set; } 
    public string imdb_id { get; set; } 
    public string epguide_name { get; set; } 
} 

public class __invalid_type__2 
{ 
    public Show2 show { get; set; } 
    public string title { get; set; } 
    public int number { get; set; } 
    public int season { get; set; } 
    public string release_date { get; set; } 
} 

public class Show3 
{ 
    public string title { get; set; } 
    public string imdb_id { get; set; } 
    public string epguide_name { get; set; } 
} 

public class __invalid_type__3 
{ 
    public Show3 show { get; set; } 
    public string title { get; set; } 
    public int number { get; set; } 
    public int season { get; set; } 
    public string release_date { get; set; } 
} 

public class Show4 
{ 
    public string title { get; set; } 
    public string imdb_id { get; set; } 
    public string epguide_name { get; set; } 
} 

public class __invalid_type__4 
{ 
    public Show4 show { get; set; } 
    public string title { get; set; } 
    public int number { get; set; } 
    public int season { get; set; } 
    public string release_date { get; set; } 
} 

public class Show5 
{ 
    public string title { get; set; } 
    public string imdb_id { get; set; } 
    public string epguide_name { get; set; } 
} 

public class __invalid_type__5 
{ 
    public Show5 show { get; set; } 
    public string title { get; set; } 
    public int number { get; set; } 
    public int season { get; set; } 
    public string release_date { get; set; } 
} 

public class Show6 
{ 
    public string title { get; set; } 
    public string imdb_id { get; set; } 
    public string epguide_name { get; set; } 
} 

public class __invalid_type__6 
{ 
    public Show6 show { get; set; } 
    public string title { get; set; } 
    public int number { get; set; } 
    public int season { get; set; } 
    public string release_date { get; set; } 
} 

public class Show7 
{ 
    public string title { get; set; } 
    public string imdb_id { get; set; } 
    public string epguide_name { get; set; } 
} 

public class __invalid_type__7 
{ 
    public Show7 show { get; set; } 
    public string title { get; set; } 
    public int number { get; set; } 
    public int season { get; set; } 
    public string release_date { get; set; } 
} 

public class RootObject 
{ 
    public List<__invalid_type__1> __invalid_name__1 { get; set; } 
    public List<__invalid_type__2> __invalid_name__2 { get; set; } 
    public List<__invalid_type__3> __invalid_name__3 { get; set; } 
    public List<__invalid_type__4> __invalid_name__4 { get; set; } 
    public List<__invalid_type__5> __invalid_name__5 { get; set; } 
    public List<__invalid_type__6> __invalid_name__6 { get; set; } 
    public List<__invalid_type__7> __invalid_name__7 { get; set; } 
} 

} 

Вот простой основной класс, чтобы распечатать его на консоль:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Text; 
using System.Threading.Tasks; 
using System.Web; 
using System.Web.Script.Serialization; 
using Newtonsoft.Json; 

namespace TvSeries 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      using (WebClient wc = new WebClient()) 
      { 
       var json = wc.DownloadString("http://epguides.frecar.no/show/gameofthrones/"); 
       //Console.WriteLine(json); 
       RootObject obj = JsonConvert.DeserializeObject<RootObject>(json); 
       foreach (var item in obj.__invalid_name__1) 
       { 
        Console.WriteLine("Show: {0}, release date: {1}", item.show.title, item.release_date); 
       } 
       Console.ReadKey(); 
      } 
     } 
    } 
} 

Так фактический вопрос, почему не десериализации или работает неправильно, поскольку объекты по-прежнему null? Мне не хватает чего-то важного? Я также пробовал JavaScriptSerializer(), но это не исправить мою проблему.

+2

У вас есть целая нагрузка классов с разными именами, которые являются одинаковыми (show1/show2 и т. д.). это создается довольно глупо по vs, потому что json, который вы вставили из возвращает список show и для каждого элемента списка, vs создал для него другой класс. упростить классы. также я предполагаю, что классы «недопустимого типа» предназначены для «Эпизода». уберите классы, и jsonconvert автоматически заполнит ваши объекты, как вы ожидаете. В настоящее время он возвращает null, потому что он не выполняет десериализацию. – user3791372

+0

В зависимости от того, что вы хотите делать с данными, вы даже можете избежать десериализации в «динамический» объект без создания классов вообще. – Jens

+0

Вы не заметили, что у вас есть куча типов с именем '__invalid_type__n'? Это должно дать вам указание. – Rob

ответ

0

используется атрибут, как это:

[JsonProperty("show")] 
public Show2 Show2 { get; set; } 
0

Как user3791372 сказал, вы должны привести в порядок сгенерированных классов. Однако эти классы генерируются, потому что ответ выглядит так: {"1": [{...} ...], "2": [{...} ...], ...}. Поэтому вам сначала нужно избавиться от «1», «2» и определить свои собственные типы для чистого кода. результат будет выглядеть так:

class Show 
{ 
    public string title { get; set; } 
    public string imdb_id { get; set; } 
    public string epguide_name { get; set; } 
} 

class Episode 
{ 
    public Show show { get; set; } 
    public string title { get; set; } 
    public int number { get; set; } 
    public int season { get; set; } 
    public DateTime release_date { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     using (WebClient wc = new WebClient()) 
     { 
      //download json string 
      var json = wc.DownloadString("http://epguides.frecar.no/show/gameofthrones/"); 
      //convert json to dynamic object 
      JObject obj = JObject.Parse(json); 
      //create an array that have as many elements as the children of obj => {"1", "2", "3", ...} 
      JArray[] results = new JArray[obj.Children().Count()]; 
      //fill the array with the children of obj => results[6] = "[{"show": {"title": "Game of Thrones", "imdb_id": "tt0944947", "epguide_name": "gameofthrones"}, "title": "TBA", "number": 1, "season": 7, "release_date": "2017-06-25"}]" 
      for (int i = 0; i < results.Length; i++) 
      { 
       results[i] = (JArray)obj[(i + 1).ToString()]; 
      } 
      //deserialize each item in results to List<Episode> if you checked the response it returns arrays of episodes 
      List<List<Episode>> seasons = new List<List<Episode>>(results.Length); 
      foreach (var item in results) 
      { 
       seasons.Add(JsonConvert.DeserializeObject<List<Episode>>(item.ToString())); 
      } 
      //output the result 
      foreach (var season in seasons) 
      { 
       foreach (var episod in season) 
       { 
        Console.WriteLine("Show: {0}, release date: {1}", episod.show.title, episod.release_date); 
       } 
      } 
      Console.ReadKey(); 
     } 

    } 
}