[英]JSON Deserialization in C# for multiple values
我有一個像這樣的JSON對象...
{
"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對象中有多個文件時,它可以按預期正常工作。 當我在JSON對象中只有一個文件時,它將向我返回0個content
文件。
如何解決這個問題?
當給定1個文件作為JSON對象時,Content變量值從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無關-與您正在創建的File對象有關。 在您給出的示例中,您嘗試設置文件的文件名,即使它為null。 嘗試在對象上設置屬性之前,請確保已實例化該對象。 Content對象很好,並且文件列表實際上包含一個文件對象。
這是您的示例,並且已修復:
var json = "{\"totalcount\":1,\"files\":[{\"filename\":\"1.txt\",\"fileContent\":\"Dineshkumar\"}]}";
JavaScriptSerializer JSSfile = new JavaScriptSerializer();
JSSfile.MaxJsonLength = Int32.MaxValue;
JSONObject Content = JSSfile.Deserialize<JSONObject>(json);
if (Content.totalcount == 1)
{
File file = new File(); //CREATE A NEW FILE OBJECT HERE <------
file.filename = Content.files[0].filename;
file.fileContent = Content.files[0].fileContent;
}
只需像這樣編輯您的JSONObject類。 比它應該起作用:
public class JSONObject
{
public int totalcount { get; set; }
public File files { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.