Я немного новичок в сериализации/десериализации строк 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(), но это не исправить мою проблему.
У вас есть целая нагрузка классов с разными именами, которые являются одинаковыми (show1/show2 и т. д.). это создается довольно глупо по vs, потому что json, который вы вставили из возвращает список show и для каждого элемента списка, vs создал для него другой класс. упростить классы. также я предполагаю, что классы «недопустимого типа» предназначены для «Эпизода». уберите классы, и jsonconvert автоматически заполнит ваши объекты, как вы ожидаете. В настоящее время он возвращает null, потому что он не выполняет десериализацию. – user3791372
В зависимости от того, что вы хотите делать с данными, вы даже можете избежать десериализации в «динамический» объект без создания классов вообще. – Jens
Вы не заметили, что у вас есть куча типов с именем '__invalid_type__n'? Это должно дать вам указание. – Rob