Deserialize json into array when object name is an integer

Viewed 100

Firstly, I know how to deserialize json into objects in general but I am still very new to C#. I am able to deserialize the json below, but the outcome is not what I would call "elegant".

{
  "slot":0,
    "io":{
      "relay":{
        "4":{
          "relayStatus":1
        }
      }
    }
 }

The issue I am having is with the relay number, "4" in this instance, as the data name in the object is an integer. The "4" could be any value from 0 to 5.

What I currently have coded is a C# object that I can reference like this..

relays.Io.Relay.Relay4.RelayStatus

Which is okay but I would like to be able to reference it like this..

relayStatus[4]

Which would be an array with a length of 6 that contains the value of "relayStatus" at position 4.

My apologies if I have not asked this question very well. Please feel free to ask for more explanation if required.

1 Answers

try this, you maybe need to add some validations, I don't know all details

   var relay =JObject.Parse(json)["io"]["relay"]
       .ToObject<Dictionary<string, JObject>>().First();

    var relayStatus = new int[6];
    var index = Convert.ToInt32(relay.Key);

    relayStatus[index] = (int) relay.Value["relayStatus"];

    var result = relayStatus[4];  // 1

but IMHO since you have only one relay status property, this code is better

var relayStatus = RelayStatus(json);

public int RelayStatus(string json)
{
    var relay = JObject.Parse(json)["io"]["relay"]
       .ToObject<Dictionary<string, JObject>>().First();

    return (int)relay.Value["relayStatus"];
}
Related