2013-04-24 82 views
0

如何爲此json創建模型?如何爲此json創建模型,c#

{"code":"1", "message":"OK","response": {"user":{"id":"124","usertype":"29","currenttime":"2013-04-24T08:09:20.487+00:00","sessionid":"2bcf1c92-9b97-47d8-8995-b39cf7cbe2af"}}}

我寫:

public class BaseResponse 
    { 
     public bool success; 
     public String message; 
    } 

    public class CreateTaskResponse : BaseResponse 
    { 
     CreateTaskResponseData data = new CreateTaskResponseData(); 

     public User getUser() 
     { 
      return data.getUser(); 
     } 
    } 

    class CreateTaskResponseData 
    { 
     User user = new User(); 
     public User getUser() 
     { 
      return user; 
     } 
    } 

public class User 
{ 
    public int id; 
    public int usertype; 
    public string currenttime; 
    public string sessionid; 
} 

和解析:

CreateTaskResponse Login = SimpleDataSerializer.ToObject<CreateTaskResponse>(response); 

錯誤: Login.getUser()會話ID爲空

+0

您是否使用了[JSON(http://james.newtonking.com/projects/json-net.aspx)解析器? – DGibbs 2013-04-24 08:38:09

+0

考慮使用JSON.NET(我個人不是粉絲,但它似乎是.NET中JSON的事實標準) – series0ne 2013-04-24 08:40:56

+0

謝謝,我會嘗試。我使用Newtonsoft.Json – 2013-04-24 08:56:29

回答

3

這是生成了什麼this site

public class User 
{ 
    public string id { get; set; } 
    public string usertype { get; set; } 
    public string currenttime { get; set; } 
    public string sessionid { get; set; } 
} 

public class Response 
{ 
    public User user { get; set; } 
} 

public class RootObject 
{ 
    public string code { get; set; } 
    public string message { get; set; } 
    public Response response { get; set; } 
} 

var obj = JsonConvert.DeserializeObject<RootObject>(json);