Jimmy Lillegaard Jimmy Lillegaard - 1 month ago 5
C# Question

Convert Json object to entity

I would like to see some of your suggestions on how to build entities in C# to fit this Json

{
"activities-heart": [
{
"dateTime": "2016-10-25",
"value": {
"customHeartRateZones": [],
"heartRateZones": [
{
"max": 88,
"min": 30,
"name": "Out of Range"
},
{
"max": 123,
"min": 88,
"name": "Fat Burn"
},
{
"max": 150,
"min": 123,
"name": "Cardio"
},
{
"max": 220,
"min": 150,
"name": "Peak"
}
]
}
}
],
"activities-heart-intraday": {
"dataset": [],
"datasetInterval": 1,
"datasetType": "minute"
}
}


This Site suggested:

public class HeartRateZone
{
public int max { get; set; }
public int min { get; set; }
public string name { get; set; }
}

public class Value
{
public List<object> customHeartRateZones { get; set; }
public List<HeartRateZone> heartRateZones { get; set; }
}

public class ActivitiesHeart
{
public string dateTime { get; set; }
public Value value { get; set; }
}

public class ActivitiesHeartIntraday
{
public List<object> dataset { get; set; }
public int datasetInterval { get; set; }
public string datasetType { get; set; }
}

public class RootObject
{
public List<ActivitiesHeart> __invalid_name__activities-heart { get; set; }
public ActivitiesHeartIntraday __invalid_name__activities-heart-intraday { get; set; }
}


My problem is that this returns nothing, it tries to build the entities but they are null. Is there something that the converter and i don't see.

Answer

Assuming you are using NewtonSoft to deserialize the json (and pretty sure that the following is also correct to other deserializers) the problem is with your classes.

If for your classes I run the following line, as you described I get null values in the properties.

var result = JsonConvert.DeserializeObject<RootObject>(jsonString);

Now if you look at the classes you have they don't even compile:

public class RootObject
{
    public List<ActivitiesHeart> __invalid_name__activities-heart { get; set; }
    public ActivitiesHeartIntraday __invalid_name__activities-heart-intraday { get; set; }
}

And the website even told you that the property names are invalid: __invalid_name__activities-heart. You can't have property names with - in them..

To fix it you need to:

  1. Change the property names in the classes to valid names + update json with new names:

    public class RootObject
    {
        public List<ActivitiesHeart> ActivitiesHeart { get; set; }
        public ActivitiesHeartIntraday ActivitiesHeartIntraday { get; set; }
    }
    
  2. Or better, change property names and then as Jim suggested use the JsonPropertyAttribute:

    public class RootObject
    {
        [JsonProperty("activities-heart")]
        public List<ActivitiesHeart> ActivitiesHeart { get; set; }
        [JsonProperty("activities-heart-intraday")]
        public ActivitiesHeartIntraday ActivitiesHeartIntraday { get; set; }
    }
    

it will work

Comments