Search code examples
c#jsonapijson-deserialization

problem deserializing object using newtonsoft


I hope someone can help me. This is code I use to retrieve a bunch of data about a particular device with an api (in this case, a Twinkly light string). Here's my code, which is partially functional.

            HttpResponseMessage result = await httpClient.GetAsync(uri);
        string response = await result.Content.ReadAsStringAsync();
        JObject jObject = JObject.Parse(response);
        Layout layout = new Layout();
        layout = JsonConvert.DeserializeObject<Layout>(response);

I say it's "partially" functional because every property that is in the root level deserializes into the model just fine, but the json also returns a property called "coordinates" which consists of an array entry for each bulb, and each entry has three values for x,y,z.
I have tried a lot of stuff to get the data from the coordinates array and i can break-mode view that the data is in there. enter image description here enter image description here

However it doesn't deserialize properly. I have the correct number of elements in the coordinates array, but they are all x:0, y:0, z:0

Here is my model schema. I hope someone can help me with this. This is my first foray into api work, and the first time i've had a nested model like this.

 internal class Layout
{ 
    public int aspectXY { get; set; }
    public int aspectXZ { get; set; }
    public LedPosition[] coordinates { get; set; } 
    public string source { get; set; } //linear, 2d, 3d
    public bool synthesized { get; set; }
    public string uuid { get; set; }
}

internal class LedPosition
{
    double x { get; set; }    
    double y { get; set; }
    double z { get; set; }
}

Note: I've tried assigning the properties manually like this:

JToken dataToken = jObject.GetValue("coordinates");

and that indeed received the data but it didn't help me as it merely moved the issue.


Solution

  • you don' t need parse and deserialized in the same time, it would be enough

     var response = await result.Content.ReadAsStringAsync();
     var layout = JsonConvert.DeserializeObject<Layout>(response);
    

    to make LedPosition properties visible make them public too

    public class LedPosition
    {
       public  double x { get; set; }    
       public double y { get; set; }
       public double z { get; set; }
    }
    

    since it is used by another class this class should be public too

    public class Layout