Reputation: 561
I have json structure like this:
{
"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!
Upvotes: 3
Views: 22009
Reputation: 11
Or you can add Name to DataContract attribute as you did for DataMember:
[DataContract (Name="emails")]
public class Emails
{
Upvotes: 0
Reputation: 31
The case of your object property must match the case in the JSON. (See bold below).
public Emails **emails** { get; set; }
{ "id":"12345", "first_name": "dino", "last_name": "he", "**emails**": { "preferred": "1", "personal": "2", "business": "3", "other": "4" }
Upvotes: 1
Reputation: 561
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.
Upvotes: 2