Miguel Moura
Miguel Moura

Reputation: 39374

Deserialize child properties from Json

I am getting the following Json from an API:

{
  "name":"xyz",
  "interval": "H1",
  "points": [
    {  
      "speed": 1431, 
      "mid": { "h": "1.07904", "l": "1.07872" }
     }
  ]
}

And I created the models:

public class Response {
  public String? Name { get; set; } 
  public IntervalEnum? Interval { get; set; }
  public List<Point> Points { get; set; } = new List<Point>();
}

public class Point {
  public Double Speed { get; set; }
  [JsonPropertyName("mid.h")]
  public Double High { get; set; }
  [JsonPropertyName("mid.l")]
  public Double Low { get; set; }
}

I am getting all values but not High and Low.

How can I parse those values?

Upvotes: 0

Views: 145

Answers (1)

Slava Knyazev
Slava Knyazev

Reputation: 6081

JsonPropertyName is for the name of a property and has no relation to the path of the property. In other words, writing [JsonPropertyName("mid.h")] you are targeting a property in an object like this:

{
  "mid.h": 5
}

The proper way to resolve this is to write your classes in a way that matches with the actual structure of the data:

public class Response {
  public String? Name { get; set; } 
  public IntervalEnum? Interval { get; set; }
  public List<Point> Points { get; set; } = new List<Point>();
}

public class Point {
  public Double Speed { get; set; }
  [JsonPropertyName("mid")]
  public MidPoint MidPoint { get; set; }
}

public class MidPoint {
  [JsonPropertyName("h")]
  public Double High { get; set; }
  [JsonPropertyName("l")]
  public Double Low { get; set; }
}

If you want to make Low and High accessible in the way you wrote it, you can write a getter for it:

public class Point {
  public Double Speed { get; set; }
  [JsonPropertyName("mid")]
  public MidPoint MidPoint { get; set; }
  public Double High => MidPoint.High;
  public Double Low => MidPoint.Low;
}

If this really doesn't suit you, you can implement your own JSON resolver: Can I specify a path in an attribute to map a property in my class to a child property in my JSON?

Upvotes: 1

Related Questions