我有這樣一個JSON對象...反序列化JSON在C#中的多個值
{
"totalcount":1,
"files":[
{
"filename":"1.txt",
"fileContent":"Dineshkumar"
}
]
}
我在C#創建了以下類。
public class File
{
public string filename { get; set; }
public string fileContent { get; set; }
}
public class JSONObject
{
public int totalcount { get; set; }
public List<File> files { get; set; }
}
我已經使用了下列對象來訪問JSON對象。現在
JavaScriptSerializer JSSfile = new JavaScriptSerializer();
JSSfile.MaxJsonLength = Int32.MaxValue;
JSONObject Content = JSSfile.Deserialize<JSONObject>(response);
我的問題是..當我在JSON對象有多於1個文件,它按預期工作完全正常。當我在JSON對象中只有一個文件時,它會返回我content
中的0個文件。
如何解決這個問題?
當1個文件給出JSON的對象,內容變量值從0
開始。如果寫這個片段爲解決這一問題,
if (Content.totalcount == 1)
{
File file = null;
file.filename = Content.files[0].filename;
file.fileContent = Content.files[0].fileContent;
File.WriteAllBytes(DestLocTxt.Text.Trim() + "\\" + file.filename, file.fileContent));
}
我得到了以下錯誤:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
問題就迎刃而解了:
{
"totalcount":1,
"files":[
{
"filename":"1.txt",
"fileContent":"Dineshkumar"
}
]
}
是預期的JSON,但服務器以不同的格式發送數據。
{
"totalcount":1,
"files": {
"filename":"1.txt",
"fileContent":"Dineshkumar"
}
}
造成由於這個問題的所有...
你能舉一個例子,你有多個文件的JSON - 問題可能與此。 –
使用http://jsonlint.com/驗證您的JSON - 您發佈的示例很好,但我猜測另一個不是。如果它是有效和正確的,你可能想切換到[Json.NET](http://james.newtonking.com/json),一個全能的更好的JSON庫。 –
@ScottGulliver我已經更新我的問題更清楚,這是因爲列表編號和反序列化。 – Dinesh