2

Hello I have this code:

trough HttpClient I recieve this json string:

{"group":3,"data":[{"count":1,"providerName":"BetaDigital","providerNo":12},{"count":139,"providerName":"Free to air","providerNo":1}]}


            var serializer = new DataContractJsonSerializer(typeof(GroupProvider));
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));

            var data = (GroupProvider) serializer.ReadObject(ms);

Then I have this classes:

[DataContract]
public class GroupProvider 
{
    public int Group { get; set; }
    public DataGroupProvider[] data { get; set; }
}

[DataContract]
public class DataGroupProvider 
{

    public int Count { get; set; }
    public string ProviderName { get; set; }
    public int ProviderNo { get; set; }
}

Problem is, that only the Group is filled and the DataGroupProvider is null..

Where is the problem?

dbc
  • 104,963
  • 20
  • 228
  • 340
petrtim
  • 267
  • 1
  • 2
  • 10

2 Answers2

2

As described in the Data Contract Basics, you either don't put DataContract attribute in which case every public property or field will be considered (but note that the names should match exactly) or put DataContract attribute and then you need to explicitly mark the members that you want to be considered with DataMember attribute. The latter also allows you to change the name mapping.

So, your sample JSon can be deserialized with either this data model (note the property name casing):

public class GroupProvider
{
    public int group { get; set; }
    public DataGroupProvider[] data { get; set; }
}

public class DataGroupProvider
{
    public int count { get; set; }
    public string providerName { get; set; }
    public int providerNo { get; set; }
}

or keeping your current property names:

[DataContract]
public class GroupProvider
{
    [DataMember(Name = "group")]
    public int Group { get; set; }
    [DataMember]
    public DataGroupProvider[] data { get; set; }
}

[DataContract]
public class DataGroupProvider
{
    [DataMember(Name = "count")]
    public int Count { get; set; }
    [DataMember(Name = "providerName")]
    public string ProviderName { get; set; }
    [DataMember(Name = "providerNo")]
    public int ProviderNo { get; set; }
}
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
0

Set an DataMember-Attribute like this:

[DataContract]
public class GroupProvider
{
    [DataMember]
    public int Group { get; set; }
    [DataMember]
    public DataGroupProvider[] data { get; set; }
}

[DataContract]
public class DataGroupProvider
{

    [DataMember]
    public int Count { get; set; }
    [DataMember]
    public string ProviderName { get; set; }
    [DataMember]
    public int ProviderNo { get; set; }
}

Then change your JSON to a correct one:

var str ="{\"Group\":3,\"data\":[{\"Count\":1,\"ProviderName\":\"BetaDigital\",\"ProviderNo\":12},{\"Count\":139,\"ProviderName\":\"Free to air\",\"ProviderNo\":1}]}";

JSON-Data is CaseSensitive

lokusking
  • 7,396
  • 13
  • 38
  • 57