0

What is the best way to flatten a Dictionary into the containing object where the keys of the dictionary are merged with the top properties?

I have the following code (I used linqpad):

void Main()
{
    Item item = new Item
    {
        Id = 1,
        Description = "Item 1",
        Attributes = new Dictionary<string, Object> {
        { "Attrib1", "Value1"},
        { "Attrib2", "Value2"}
        }
    };

    string json = JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented);

    json.Dump();
}   

// Define other methods and classes here
class Item
{
    public int Id { get; set; }
    public String Description { get; set; }
    public Dictionary<String, Object> Attributes { get; set; }
}

By default it gets serialized to:

{
  "Id": 1,
  "Description": "Item 1",
  "Attributes": {
    "Attrib1": "Value1",
    "Attrib2": "Value2"
  }
}

I want to get it serialized to:

{
  "Id": 1,
  "Description": "Item 1",
  "Attrib1": "Value1",
  "Attrib2": "Value2"
}

Other assumptions:

  • the keys in the Attributes should be preserved as they are
  • any key with the same name as a property of the Item class should be ignored.
  • the class has only one collection (Attributes) that would have to be pulled in the contained object

Is there a trick that can do it sort of out-of-the-box, or should I create a custom converter?

Thanks

boggy
  • 3,674
  • 3
  • 33
  • 56
  • 1
    What will happen if item has two dictionaries each having key/value pairs {a1:v1} and {a2:v2}? – treehouse Aug 28 '17 at 19:12
  • Very good question. Item will always have one collection. It is possible to have an attribute name "Id" or "Description". In that case, the Item Id and Description properties should take precedence and those attributes from the dictionary should be ignored. – boggy Aug 28 '17 at 19:16
  • This is very specialized logic. I suggest using custom json converter. – treehouse Aug 28 '17 at 19:35
  • Brian, thank you for pointing me to the article. Before I posted mine, I did search for something similar but I didn't find it, otherwise I would not have wasted the time to write mine. – boggy Aug 28 '17 at 19:45
  • @costa No worries - it happens all the time. – Brian Rogers Aug 28 '17 at 20:38

0 Answers0