-1

Having to decode an unusually-formatted JSON array, where instead of being an array, the contents are complete objects:

{
    "133v1": {
        "128": "2024-01-24",
        "155": "2024-04-01",
        "1066": "2024-05-16",
        "1198": "2024-09-25"
    },
    "1092v8": {
        "589": "2024-12-23"
    }
}

Sadly, I cannot change the incoming JSON, as it's coming from one of our mainframes. The names of the objects (eg: 1092v8 and 133v1) can change each time, and so can the values contained. The number of objects can also vary - sometimes we'll only be getting one. Sometimes, upwards to 3k.

Because of this I can't create a POCO to decode the JSON into. I've tried decoding the root object into a JObject (JObject sensorObj = JObject.Parse(sensors);) which will give me some data - and I can looop through each child. But then trying to get each key/value in the child is proving oddly difficult; I'm missing something that (I feel?) should be more obvious.

Currently I'm using the following loop -

foreach (var item in versionOb.Children())
{
    //Loop through each version.
    foreach (var sensor in item.Children().Single().Children())
    {
        //Get the date - 
        string date = ((dynamic)sensor.Values().Single()).Value;
        //Get the sensor readings
        string sendorReading = ((dynamic)sensor).Name;
    }
}

For some reason I need to use the .Name and .Value properties, after casting them to a Dynamic, becuase a JToken doesn't seem to have these properties available.

Is there a better way to get these values?

Edit: As mentioned, it's less along the lines of a string, string dictionary, because of the parent level.

2
  • 5
    Looks like a Dictionary<string,Dictionary<string,string>> to me Commented Dec 28, 2024 at 23:38
  • @Progman Not a duplicate, not a string string because of the parent layer. This DOES help with the base values (the date and sensorReading, but the parent foreach should be easier to handle as well. :D Commented Dec 29, 2024 at 1:03

1 Answer 1

0

Welp, thanks to How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET? - this did give me a thought to try - Since each object is (literally) a key with a collection of key-value pairs, the following line successfully turns the JSON into a useable object -

var temp = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(sensorsJson);

This likely wouldn't work if the schema of the JSON was altered in any way, but in the above case, it certainly worked.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.