C# 如何将 DataContractJsonSerializer 用于 Json?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14959698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use DataContractJsonSerializer for Json?
提问by EthenHY
I have json structure like this:
我有这样的json结构:
{
"id":"12345",
"first_name": "dino",
"last_name": "he",
"emails": {
"preferred": "1",
"personal": "2",
"business": "3",
"other": "4"
}
}
I want to get the value in Emails So I write two class:
我想获取电子邮件中的值所以我写了两个类:
[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; }
}
And I write code like this:
我写这样的代码:
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();
For info, I can get other value in UserInformation, But for Emails I get nothing. Why, And how should I write the class? Please help me!
对于信息,我可以在 UserInformation 中获得其他值,但对于电子邮件,我一无所获。为什么,我应该如何编写类?请帮我!
采纳答案by EthenHY
I found the problem is I need to change all my property in Emails to lower case... I don't know why.. But it worked.
我发现问题是我需要将电子邮件中的所有属性更改为小写...我不知道为什么...但它有效。
回答by user2676032
The case of your object property must match the case in the JSON. (See bold below).
对象属性的大小写必须与 JSON 中的大小写匹配。(见下面的粗体)。
public Emails **emails** { get; set; }
{ "id":"12345", "first_name": "dino", "last_name": "he", "**emails**": { "preferred": "1", "personal": "2", "business": "3", "other": "4" }
回答by ambek.net
Or you can add Name to DataContract attribute as you did for DataMember:
或者您可以像为 DataMember 所做的那样将 Name 添加到 DataContract 属性:
[DataContract (Name="emails")]
public class Emails
{