Как десериализовать многомерный JSON - PullRequest
1 голос
/ 17 марта 2020

Я знаю, что люди спрашивали и уже получили некоторые ответы на очень похожий вопрос до , как этот , но, тем не менее, я не мог понять это о моем. У меня JSON файл содержит многомерный объект, как показано ниже:

{
      "Common": {
        "Required": "Required Entry ",
        "Photos": "Photos",
        "Videos": "Videos",
        "Register": "Register"
      },
      "Forms": {
        "Form": "Forms",
        "Name": "Name",
        "Phone": "Phone",
        "Email": "Email",
        "Message": "Message"
      },
      "Sections": {
        "Home": {
          "EventDateTime": "",
          "MainTitle": "",
          "SubTitle": ""
        },
        "About": {},
        "Venue": {},
        "Schedule": {},
        "Speakers": {},
        "Sponsors": {},
        "Price": {},
        "Contact": {}
      }
    }

Я хотел бы десериализовать его в свою модель представления (LanguagesViewModel), например:

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class LanguagesViewModel
{
    public Common Common { get; set; }
    public Buttons Buttons { get; set; }
    public Forms Forms { get; set; }
    public Navbar Navbar { get; set; }
    public Sections Sections { get; set; }
}

public class Common
{
    public string Required { get; set; }
    public string Photos { get; set; }
    public string Videos { get; set; }
    public string Register { get; set; }
}

public class Forms
{
    public string Form { get; set; }
    public string Name { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public string Message { get; set; }
}

public class Sections
{
    public Home Home { get; set; }
    public About About { get; set; }
    public Venue Venue { get; set; }
    public Schedule Schedule { get; set; }
    public Speakers Speakers { get; set; }
    public Sponsors Sponsors { get; set; }
    public Price Price { get; set; }
    public Contact Contact { get; set; }
}

public class Home
{
    public string EventDateTime { get; set; }
    public string MainTitle { get; set; }
    public string SubTitle { get; set; }
}

public class About
{

}

public class Venue
{

}

public class Schedule
{

}

public class Speakers
{

}

public class Sponsors
{

}

public class Price
{

}

public class Contact
{

}

}

Некоторые фрагменты для этого:

using (StreamReader sr = new StreamReader(language_file_path))
{
    string contents = sr.ReadToEnd();
    items = JsonConvert.DeserializeObject<LanguagesViewModel>(contents);
}

Каким-то образом я могу получить только первый уровень объектов, а именно:

LanguagesViewModel{
    Common:null,
    Forms:null,
    Sections:null
}

Не второй уровень, а не третий уровень. Я сделал что-то не так или я что-то пропустил? Очень признателен за любую помощь.

Спасибо.

1 Ответ

2 голосов
/ 17 марта 2020

Вы можете использовать этот класс c класс

public static class JsonHelper 
{
    public static T ToObject<T>(this string content)
    {
        var obj = JObject.Parse(content).GetValue(typeof(T).Name);

        if (obj == null)
            throw new NullReferenceException();
        else
            return obj.ToObject<T>();
        //This ToObject here is default method written in object
    }
}

Использование

var mymodel= json.ToObject<Forms>();

Или создать объект JSON и прочитать его со строками magi c.

//Creating your JSON object
JObject content = JObject.Parse(sr.ReadToEnd()//or your json);

//content["your object name"] let you access to you object
var common =(Common)content["Common"];

в многомерных объектах, вы можете получить к ним доступ следующим образом.

 //content["level1"]["level2"]["level3"] & ...
 var sections= (Home)content["Sections"]["Home"];

Также этот способ может работать, но я предпочитаю способ с волшебные c строки.

dynamic jsonObject = new JObject.Parse(sr.ReadToEnd());
var common = jsonObject.Common;

Вы можете найти больше в этой ссылке

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...