3

我有这样的json结构:

{
   "id":"12345",
   "first_name": "dino",
   "last_name": "he",
   "emails": {
      "preferred": "1",
      "personal": "2",
      "business": "3",
      "other": "4"
   }
}

我想在电子邮件中获得价值所以我写了两个类:

[DataContract]
public class UserInformation
{
    [DataMember(Name = "id")]
    public string ID { get; set; }
    [DataMember(Name = "emails")]
    public Emails emails { get; set; }
    [DataMember(Name = "last_name")]
    public string Name { get; set; }

}
[DataContract]
public class Emails
{
    [DataMember(Name = "preferred")]
    public string Preferred { get; set; }


    [DataMember(Name = "personal")]
    public string Account { get; set; }

    [DataMember(Name = "business")]
    public string Personal { get; set; }

    [DataMember(Name = "other")]
    public string Business { get; set; }
}

我写这样的代码:

StreamReader stream = new StreamReader(@"C:\Visual Studio 2012\Projects\ASP.net\WebApplication1\WebApplication2\TextFile1.txt");
string text = stream.ReadToEnd();
stream.Close();

byte[] byteArray = Encoding.UTF8.GetBytes(text);
MemoryStream stream1 = new MemoryStream(byteArray);


DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UserInformation));
var info = serializer.ReadObject(stream1) as UserInformation;
stream1.Close();

对于信息,我可以在 UserInformation 中获得其他价值,但对于电子邮件,我什么也得不到。为什么,我应该如何写这门课?请帮我!

4

3 回答 3

2

我发现问题是我需要将电子邮件中的所有属性更改为小写......我不知道为什么......但它有效。

于 2013-02-20T02:55:46.507 回答
1

您的对象属性的大小写必须与 JSON 中的大小写匹配。(见下面的粗体字)。

public Emails **emails** { get; set; }

{ "id":"12345", "first_name": "dino", "last_name": "he", "**emails**": { "preferred": "1", "personal": "2", "business": "3", "other": "4" }
于 2014-07-03T14:23:21.690 回答
0

或者您可以像为 DataMember 所做的那样将 Name 添加到 DataContract 属性:

[DataContract (Name="emails")]
public class Emails
{
于 2020-01-09T09:12:14.210 回答