Home > front end >  Flatten object with collection properties
Flatten object with collection properties

Time:03-17

Suppose that I have a following object instantiated.

public class Parent
    {
        public int Id { get; set; }
        public string Name { get; set; }

        [JsonExtensionData]
        public IReadOnlyDictionary<string, string> AdditionalProperties { get; set; }
    }

Parent parent = new() { Id = 1, Name = "Parent", AdditionalProperties = new Dictionary<string, string>() { { "Property", "SomeProperty" } } };

This would be translated to the following JSON structure:

 parent {
           id: 1,
           name: "parent",
           additionalProperties: {
             property: "someProperty
           }
         }

Instead I would like to flatten it and return the following json object to the user.

 parent {
           id: 1,
           name: "parent",
           property: "someProperty"
        }

I could handle additional properties with dynamic or extendo objects but I don't want this, I need it as strongly typed as possible, so I decided to store dynamic properties inside the dictionary.

CodePudding user response:

Unfortunately you didn't tell us, which JSON serializer you are using, so I tested Microsoft and Newtonsoft. Both will throw an error if your property is of type IReadOnlyDictionary<string, string>, but if you change it to be Dictionary<string, object> it enter image description here

After enter image description here Source: Tutorial

  • Related