我對JSON相當陌生,特別是序列化和反序列化。我有這樣的JSON,我首先序列化並放入變量。現在我想從這個變量中獲取數據。如何使用newtonsoft反序列化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內的列表項,不只是一個......我可以有100個類別。如何讓這些物品回來?
我應該怎麼做?
謝謝!
編輯
public class Books
{
public string title {get;set;}
public string bookNumber {get;set;}
public List<aisle> aisles {get;set;}
}
PS - 低/大寫不是問題!它是由於英文翻譯
如果您分類_categories = JsonConvert.DeserializeObject(_myJson); 您沒有分類嗎? –
JBO
什麼是Books類的聲明? – raichiks
請參閱編輯請@raichiks – aiden87