2014-04-01 104 views
1
json="{\n \"kind\": \"plus#person\", 
    \n \"etag\": \"\\\"GjejyguyfTE/pdfBI8xyufoiuh9bOLZ8VyG_8\\\"\", 
    \n \"gender\": \"male\", 
    \n \"emails\": [\n {\n \"value\": \"[email protected]\",\n \"type\": \"account\"\n }\n ], 
    \n \"objectType\": \"person\", 
    \n \"id\": \"xxxxxxxxxxxxxxx\", 
    \n \"displayName\": \"XXXXXXXXX XXXXXXX\", 
    \n \"name\": {\n \"familyName\": \"XXXXXX\",\n \"givenName\": \"XXXXXX\"\n }, 
    \n \"url\": \"https://plus.google.com/xxxxxxxxxxxxxxx\", 
    \n \"image\": {\n \"url\": \"https://lh3.googleusercontent.com/-XdUWA/AAAAAAI/AAbbbbAA/42hhscbv5M/photo.jpg?sz=70\"\n }, 
    \n \"isPlusUser\": true, 
    \n \"language\": \"en\", 
    \n \"ageRange\": {\n \"min\": 21\n }, 
    \n \"circledByCount\": 0, 
    \n \"verified\": false\n}\n" 



public class GoogleUser 
    { 
     public string kind { get; set; } 
     public string etag { get; set; } 
     public string gender { get; set; } 
     public Email[] emails { get; set; } 
     public string objectType { get; set; } 
     public string id { get; set; } 
     public string displayName { get; set; } 
     public Name name { get; set; } 
     public string url { get; set; } 
     public Image image { get; set; } 
     public bool isPlusUser { get; set; } 
     public string language { get; set; } 
     public AgeRange ageRange { get; set; } 
     public int circledByCount { get; set; } 
     public bool verified { get; set; } 
    } 

    public class Name 
    { 
     public string familyName { get; set; } 
     public string givenName { get; set; } 
    } 

    public class Email 
    { 
     public string value { get; set; } 
     public string type { get; set; } 
    } 
    public class Image 
    { 
     public string url { get; set; } 
    } 
    public class AgeRange 
    { 
     public int min { get; set; } 
    } 





GoogleUser user = new JavaScriptSerializer().Deserialize<GoogleUser>(json); 

我在C# 4.0 發展我在項目中使用login with google+按鈕。 我想通過使用access_token來獲取用戶。 我可以將它們作爲json filen。 然後我想複製他們我的GoogleUser class。 我沒有得到錯誤,但user總是等於null。 通過這種方式,昨天我可以獲取用戶的數據,但不是今天。反序列化JSON到類在C#

什麼是我的問題?

<code>string a</code> is not <code>null</code>, it is my <code>json</code> file, but <code>user</code> is <code>null</code>

+0

你發佈的代碼似乎工作... – sloth

+0

第一件事;瀏覽器可能會緩存請求/數據,並搞砸了事情(鉻是善於搞砸JavaScript緩存),其次;由於多種原因,我會使用JsonProperty屬性,例如[JsonProperty(「kind」)]然後Propercase屬性。 –

+0

我會嘗試JsonProperty,但它通過這種方式昨天工作。 – Jeyhun

回答

2

你可以嘗試:

user = new JavaScriptSerializer().Deserialize<A>(a); 

既然你說 「是」 有字符串中的價值。也許問題是你正在調用ReadToEnd兩次?

+0

我在發佈我的問題後添加了圖片,因此其他用戶看不到它, 非常感謝,現在它能正常工作。我今天添加了'string a') – Jeyhun

+0

例如我在'json'文件中有'name ='Jeyhun'''surname =「Elvin」'' 我只想得到'name'。 我是否有義務在我的'USERS'類'surname'中聲明? 或者足夠了 'USERS class {public string name {get;設置;}}' – Jeyhun

+0

我會說試試看。我不確定。我認爲它會起作用。 – Derek