2014-01-09 15 views
0

我有這樣一個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" 
} 
} 

造成由於這個問題的所有...

+0

你能舉一個例子,你有多個文件的JSON - 問題可能與此。 –

+2

使用http://jsonlint.com/驗證您的JSON - 您發佈的示例很好,但我猜測另一個不是。如果它是有效和正確的,你可能想切換到[Json.NET](http://james.newtonking.com/json),一個全能的更好的JSON庫。 –

+0

@ScottGulliver我已經更新我的問題更清楚,這是因爲列表編號和反序列化。 – Dinesh

回答

0

這裏的問題是不是與JSON - 這是你所創建的文件對象。在你給出的例子中,你試圖設置文件的文件名,即使它是空的。在嘗試設置對象之前,確保對象實際被實例化。內容對象很好,文件列表實際上包含一個文件對象。

這就是你們的榜樣,與地方的修補程序:

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; 
} 
+0

有了這個新的對象也是同樣的問題:(..問題是我猜解串行..'content'不來正確:( – Dinesh

+0

奇怪 - 這個例子中,我工作得很好,你是否嘗試過放置一個斷點後。反序列化是爲了檢查內容對象? –

+0

@Scottt這一切問題,由於服務器。感謝派出了很多幫助,以解決這個問題不同的JSON。 – Dinesh

0

只需編輯您的JSONObject級這樣。比它應該工作:

public class JSONObject 
{ 
public int totalcount { get; set; } 
public File files { get; set; } 
} 
+0

文件是一個數組,所以即使你的代碼的工作,它會崩潰時,他會收到多個文件。 –