2

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.

8
  • 1
    Does this answer your question? How can I parse a JSON string that would cause illegal C# identifiers?, Deserializing JSON with dynamic keys Commented Jun 24, 2022 at 7:11
  • Just to clarify, in this particular example you would like to have an relayStatus array with length 6 which contains 1 Relay object and 5 nulls. Is my understanding correct? Commented Jun 24, 2022 at 7:54
  • You need to declare relay as a Dictionary<int, Relay> and then the dictionary will have a key 4 Commented Jun 24, 2022 at 8:23
  • @Charlieface I've tried to do this but failed. Are you able to provide a quick example? Commented Jun 24, 2022 at 9:18
  • @YongShun I think it might but I couldn't get the example provided in that post to work. The dictionary had the keys of 1 and 2 but the values were "json_testing.Class3+Item" not the json objects? Commented Jun 24, 2022 at 9:19

1 Answer 1

1

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"];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! The first piece of code that you provided does exactly what I was trying to achieve. What's more, you wrote in a way that a noob like me could understand what was going on.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.