如何用newtonsoft反序列化json

时间:2017-08-01 07:44:20

标签: c# json serialization deserialization

我对JSON很新,特别是序列化和反序列化。我有这样的JSON,我首先序列化并将其放在变量中。现在我想从这个变量中获取数据。

{
    "timestamp": "2017-06-20 12:12:10",
    "categories":
[
    {
      "name": "Fiction",
    },
    {
      "name": "Roman",    
    }
]
,
    "types":
[
    {
      "name": "Long story",
    },
    {
      "name": "Short story",      
    }
],
    "books":
[
    {
        "title": "Song of ice and fire",
        "bookNumber": "1234567",
        "aisle":
        [
            {
                "location": "fiction isle",
            },
            {
                "location": "roman aisle",
            }
        ]
    }
]
}

存储在我的var json

**更新1 **

    public List<Books> listOfBooks()
        {
            var bookList = new List<Books>
            {
                new Books
                {
                    title = "song of ice and fire"
                    bookNumber = "1234567",
                    aisle = listOfAisles()           
                }
            };
            return bookList;
        }

public List<Aisle> listOfAisles
{
        var aisleList = new List<Aisle>
            {
                new Aisle
                {
                    location = "fiction aisle"

                }
            };
            return aisleList;
}

MainProgram registerBooks = new MainProgram();
        var obj = new MainProgram
        {
            Timestamp = "2017-06-20 09:10:55",
            Books = listOfBooks(),
            listOfAisles = listOfAisles(),
            categories = listOfCategories(),
            types = listofTypes()
        };

var _myJson = new JavaScriptSerializer().Serialize(object);

Books _books = JsonConvert.DeserializeObject<Books>(_myJson);

string _time = _books.Timestamp;

当我调试我得到时间戳并把它放在_time并且它工作正常...但是当我尝试获取其他项目如categories.name时,我无法达到这些项目。

问题是我可能在这个JSON中有很多List项目,而不仅仅是一个...我可能有100个类别。如何取回这些物品?

我该怎么做?

谢谢!

修改

public class Books
{
    public string title {get;set;}
    public string bookNumber {get;set;}
    public List<aisle> aisles {get;set;}
}

PS - 低/大写不是问题!它应该翻译成英文

1 个答案:

答案 0 :(得分:1)

类别是列表中的列表。所以,如果你想得到它们。通过linq查找特定类别或迭代foreach库并打印所有类别。取决于需求。

Library library = JsonConvert.DeserializeObject<Library>(_myJson);
//find category by name
Category finddedCategory = library.categories.FirstOrDefault(x => x.name == "sci-fi");
//print out all names of categories
foreach(Category c in library.categories)
{
 Console.Write(c.name);
}