2014-12-23 131 views
-2

我想從下面給出的JSON中獲得'id'。請建議來自嵌套json響應的數據

{ 
    "User": { 
     "User": { 
      "id": "3", 
      "first_name": "ABC", 
      "last_name": "Kumar", 
      "email": "[email protected]", 
      "role": "admin" 
     } 
    } 
} 

我已經使用下面的代碼進行反序列化。但無法從json訪問id。

JavaScriptSerializer serializer = new JavaScriptSerializer(); 
//var json = new JavaScriptSerializer().Serialize(Usercontent); 
Object LoginUser = serializer.DeserializeObject(LoginUserDetails); 
Dictionary<string, object> countList = (Dictionary<string, object>)LoginUser; 
+0

您是否能夠獲得其他屬性?你的'LoginUserDetails'類型*有* Id屬性嗎?目前還不清楚爲什麼你有這個嵌套開始,請關注你。 –

回答

1

嵌套的Json需要嵌套類。

//json string... I had to remove the double quotes to make it clearer. 
string jsonString = @"{ 
    'User': { 
     'User': { 
      'id': '3', 
      'first_name': 'ABC', 
      'last_name': 'Kumar', 
      'email': '[email protected]', 
      'role': 'admin' 
     } 
    } 
}"; 

JavaScriptSerializer js = new JavaScriptSerializer(); 
object obj = js.Deserialize(jsonString, typeof(User1)); 
User1 k = (User1)obj; 

//id can be accessed by 
int userid = k.User.User.id; 

//nested user class 
namespace JsonTest 
{ 
    //main user 
    public class User1 
    { 
     public User2 User; 
    } 
    //user2 is nested in user 1 
    public class User2 
    { 
     public User User; 
    } 
    //final user is nested in User2. 
    //note that the property name is User in all cases. 
    public class User 
    { 
     public int id { get; set; } 
     public string first_name { get; set; } 
     public string last_name { get; set; } 
     public string email { get; set; } 
     public string role { get; set; } 
    } 


}