Jake
Jake

Reputation: 23

Deserializing JSON into a C# class with dynamic field names

My question is very similar to this one. I tried adapting their solution to fit my needs but can't seem to figure out the solution for my JSON.

Here is an example of the JSON:

{
  "0fea8f8a-4169-495d-8307-50bc333fd87d": {
    "serviceId": "4cb9125a-1eaa-4bd4-a473-cfccec0f3c63"
  },
  "0564d078-94f5-4f97-8398-b9f58a51f70b": {
    "serviceId": "00000000-0000-0000-0000-000000000000"
  },
  "f9a165d2-967d-4733-8599-1074270dae2e": {
    "serviceId": "00000000-0000-0000-0000-000000000000"
  },
  "86ccdsbf-e7ad-4851-93ff-6ec817469c1e": {
    "serviceId": "00000000-0000-0000-0000-000000000000"
  }
}

As you can see, it is a series (not an array) of Id_1 : {serviceId: Id_2}

I think this can most simply be represented in a C# class as something like this: List<KeyValuePair<string, string>>, basically a List of <Id_1, Id_2>, but I'm open to alternatives.

Here is my attempt at a solution based on the linked post above:

class PolicyMetadata
    {
        [JsonConverter(typeof(MetadataConverter))]
        public KeyValuePair<string,string>[] idPairs { get; set; }

    }

class MetadataConverter : JsonConverter
{

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // deserialize as object
        var pairs = serializer.Deserialize<JObject>(reader);
        var result = new List<KeyValuePair<string, string>>();

        // create an array out of the properties
        foreach (JProperty property in pairs.Properties())
        {
            var pair = property.Value.ToObject<KeyValuePair<string, string>>();
            result.Add(pair);
        }

        return result.ToArray();
    }



    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(KeyValuePair<string, string>[]);
    }
}

And I call it here: var response = JsonConvert.DeserializeObject<PolicyMetadata>(content); But this resuts in a null value, so I am definitely doing something wrong. I tried placing breakpoints and print statements throughout the ReadJson method, but they were never triggered, so I'm not sure if that code is actually running.

Upvotes: 1

Views: 233

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 14231

Model:

public class Service
{
    public string ServiceId { get; set; }
}

Use dictionary:

static void Main()
{
    string json = @"
{
    ""0fea8f8a-4169-495d-8307-50bc333fd87d"": {
    ""serviceId"": ""4cb9125a-1eaa-4bd4-a473-cfccec0f3c63""
    },
    ""0564d078-94f5-4f97-8398-b9f58a51f70b"": {
    ""serviceId"": ""00000000-0000-0000-0000-000000000000""
    },
    ""f9a165d2-967d-4733-8599-1074270dae2e"": {
    ""serviceId"": ""00000000-0000-0000-0000-000000000000""
    },
    ""86ccdsbf-e7ad-4851-93ff-6ec817469c1e"": {
    ""serviceId"": ""00000000-0000-0000-0000-000000000000""
    }
}";

    var result = JsonConvert.DeserializeObject<Dictionary<string, Service>>(json);

    foreach (var pair in result)
    {
        Console.WriteLine("Key: " + pair.Key + " ServiceId: " + pair.Value.ServiceId);
    }
}

Upvotes: 2

Related Questions