2013-03-26 137 views
5

我得到以下JSON數據如何解析JSON對象在C#中

[{"id":"1","text":"System Admin","target":{"jQuery1710835279177001846":12},"checked":true,"state":"open"}, 
{"id":"2","text":"HRMS","target":{"jQuery1710835279177001846":34},"checked":false,"state":"open"}, 
{"id":"3","text":"SDBMS","target":{"jQuery1710835279177001846":42},"checked":false}, 
{"id":"8","text":"Admin","target":{"jQuery1710835279177001846":43},"checked":false}, 
{"id":"9","text":"My test Admin","target":{"jQuery1710835279177001846":44},"checked":false,"state":"open"}, 
{"id":"24","text":"ModuleName","target":{"jQuery1710835279177001846":46},"checked":false,"state":"open"}] 

它嘗試使用Json.Net使用強於解析型

這是我的財產類

public class testclass 
    { 
     public string id { get; set; } 
     public string text { get; set; } 
     public string @checked { get; set; } 
     public string state { get; set; } 
     public target jQuery1710835279177001846 { get; set; } 

    } 
    public class testclass2 
    { 
     public List<testclass> testclass1 { get; set; } 

    } 

    public class target 
    { 
     public string jQuery1710835279177001846 { get; set; } 
    } 

這裏我試圖訪問我收到的數據異常

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'QuexstERP.Web.UI.Areas.SysAdmin.Controllers.testclass' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. 

我的控制器代碼的樣子

public void Test(string Name, object modeldata) 
     { 

      var obj = JsonConvert.DeserializeObject<testclass>(Name); 

     } 

任何想法如何解決在C#這個問題

回答

8

你的JSON字符串看起來有序列化數組對象,因爲它包含[ ]。這意味着你有一個Json字符串,它是在數組對象序列化後形成的。所以,你需要反序列化到數組對象,那麼試試這個

var obj = JsonConvert.DeserializeObject<List<testclass>>(jsonString); 
3

你的TestClass的陣列。所以它應該是這樣的。

var model= JsonConvert.DeserializeObject<List<testclass>>(Name); 

爲什麼你使用JSonConvert?在MVC3你可以做這樣的

return Json(yourmodel,JsonRequestBehavior.AllowGet); 
+0

我想要得到的數據從視圖到服務器端 – 2013-03-26 10:38:51

1

你的JSON對象都是這樣

{ 
     "id":"1", 
     "text":"System Admin", 
     "target":{ 
     "jQuery1710835279177001846":12 
     }, 
     "checked":true, 
     "state":"open" 
} 

它應該是這樣的我想

{ 
     "id":"1", 
     "text":"System Admin", 
     "jQuery1710835279177001846":12, 
     "checked":true, 
     "state":"open" 
}