在C#中将json反序列化为类

时间:2014-04-01 12:08:39

标签: c# json class

json="{\n \"kind\": \"plus#person\",
    \n \"etag\": \"\\\"GjejyguyfTE/pdfBI8xyufoiuh9bOLZ8VyG_8\\\"\",
    \n \"gender\": \"male\",
    \n \"emails\": [\n  {\n   \"value\": \"example@gmail.com\",\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。 通过这种方式,昨天我可以得到用户的数据,但不是今天。

我的问题是什么?

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

1 个答案:

答案 0 :(得分:2)

你可以尝试:

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

因为你说“a”在字符串中有值。也许问题是你两次调用ReadToEnd?