0

We have the following Json

{
  "@message": "some message",
  "outputs": {
    "outone": {
      "value": "eastus2"
    },
    "outtwo": {
      "value": "r7ty-network"
    }
  }
}

the outputs section contain 2 objects "outone" and "outtwo", we are struggling to get hold of the the names "outone" and "outtwo" and its corresponding value property.

we generated c# classes and everything was working as expected, but later we were told that the values "outone" and "outtwo",are dynamic, they can be named anything.

any pointers will help.

Thanks -Nen

nen
  • 621
  • 2
  • 10
  • 26
  • Does this answer your question? [json deserialization to C# with dynamic keys](https://stackoverflow.com/questions/65727513/json-deserialization-to-c-sharp-with-dynamic-keys) Use `Dictionary outputs` and create a class `class ValueObject { public string value; }` – Charlieface Nov 05 '21 at 10:52

2 Answers2

0

try this code using Newtonsoft.Json

var jsonDeserialized= JsonConvert.DeserializeObject<Data>(json);

and classes

public partial class Data
{
    [JsonProperty("@message")]
    public string Message { get; set; }

    [JsonProperty("outputs")]
    public Dictionary<string,Out> Outputs { get; set; }
}

public partial class Out
{
    [JsonProperty("value")]
    public string Value { get; set; }
}
Serge
  • 40,935
  • 4
  • 18
  • 45
0

I assume you want to have some kind of key value list. Here's a demo in form of a test that's green:

UPDATE: Took care of eventual duplicate "keys"

[TestMethod]
public void JObject_Test()
{
    var jObject = JObject.Parse(
        @"{
            ""@message"": ""some message"",
            ""outputs"": {
              ""outone"": {
                ""value"": ""eastus2""
              },
              ""outtwo"": {
                ""value"": ""r7ty-network""
              }
            }
        }");

    var outputs = new List<KeyValuePair<string, string>>();

    foreach (var jproperty in jObject["outputs"].Children<JProperty>())
    {
        outputs.Add(
            new KeyValuePair<string, string>(jproperty.Name,
                (string)((JObject)jproperty.Value)["value"]));
    }

    Assert.AreEqual("outone", outputs[0].Key);
    Assert.AreEqual("eastus2", outputs[0].Value);

    Assert.AreEqual("outtwo", outputs[1].Key);
    Assert.AreEqual("r7ty-network", outputs[1].Value);
}
Florian Schmidinger
  • 4,682
  • 2
  • 16
  • 28