我的json数据是这样的
"{\"total_entries\":2,\"current_page\":1,\"total_pages\":1,\"per_page\":2,\"items\":[{\"workspace\":{\"background_color\":\"#ffedd3\",\"data_room\":false,\"default_sort\":\"alphabetical\",\"default_view\":\"list\",\"id\":330201,\"name\":\"MyWorkSpaceNew\",\"updated_at\":\"2013-05-08T05:54:25-07:00\",\"root_folder_id\":166325721,\"owner_id\":991101,\"is_owner\":true,\"effective_role\":\"Administrator\",\"audit_trail\":true,\"require_agreement\":false,\"agreement_accepted\":false}},{\"workspace\":{\"background_color\":\"white\",\"data_room\":false,\"default_sort\":\"alphabetical\",\"default_view\":\"list\",\"id\":343316,\"name\":\"qqq\",\"updated_at\":\"2013-05-12T22:34:08-07:00\",\"root_folder_id\":179855446,\"owner_id\":991101,\"is_owner\":true,\"effective_role\":\"Administrator\",\"audit_trail\":true,\"require_agreement\":false,\"agreement_accepted\":false}}]}"
我想要对json数据进行deserilize 我的C#代码就像
workspacename data = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<workspacename>(responseText);
我希望反序列化数据我得到total_entries,items count,per_page但是在工作区内我得到的每件事都空了
public class workspacename
{
public int total_entries { get; set; }//getting value
public int current_page { get; set; }//getting value
public int total_pages { get; set; }//getting value
public int per_page { get; set; }//getting value
public List<items> items { get; set; }// items count 2 but value null.
}
public class items
{
// public List<workspace> workspace { get; set; }
public string background_color { get; set; }
public bool data_room { get; set; }
public string default_sort { get; set; }
public string default_view { get; set; }
public int id { get; set; }
public string name { get; set; }
public DateTime updated_at { get; set; }
public int root_folder_id { get; set; }
public int owner_id { get; set; }
public bool is_owner { get; set; }
public string effective_role { get; set; }
public bool audit_trail { get; set; }
public bool require_agreement { get; set; }
public bool agreement_accepted { get; set; }
}
答案 0 :(得分:0)
改为使用DataContractJsonSerializer:
您应该使用属性定义数据类:
[DataContract]
public class workspacename
{
[DataMember]
public int total_entries { get; set; }//getting value
[DataMember]
public int current_page { get; set; }//getting value
...
和
[DataContract]
public class items
{
[DataMember]
public string background_color { get; set; }
[DataMember]
public bool data_room { get; set; }
...
然后你应该对你的json对象进行deserilize:
var serializer = new DataContractJsonSerializer(typeof(workspacename));
using (var stream = new MemoryStream())
{
var asBytes = Encoding.UTF8.GetBytes(jsonObjectString);
stream.Write(asBytes, 0, asBytes.Length);
stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
var yourDeserializedWorkspacename= (workspacename)serializer.ReadObject(stream);
}
答案 1 :(得分:0)
使用Newtonsoft.Json
会很简单:
workspacename obj = JsonConvert.DeserializeObject<workspacename>(inputJson)
值得注意的是,最好坚持命名约定:
workspacename => WorkSpaceName
total_entries => TotalEntries