0

I have a blob of JSON that I'm reading in C# using the Newtonsoft JSON.NET library. The content within "data" are dynamically named objects. So I won't know when reading the data that the first object might be named "ABC123". Since each one of these objects within "data" has the same schema it would be easiest for me to convert this into an array.

Convert:

data: {
    ABC123: { id: 1, name: "Name 1" },
    XYZ789: { id: 2, name: "Name 2" },
    QRS456: { id: 3, name: "Name 3" },
    TUV678: { id: 4, name: "Name 4" }
}

To:

data: [
    { id: 1, name: "Name 1" },
    { id: 2, name: "Name 2" },
    { id: 3, name: "Name 3" },
    { id: 4, name: "Name 4" }
]

How would I do this using JSON.NET? I'm hoping to achieve this using a serialization attribute so that I don't have to loop through the objects.

  • 5
    Deserialize to a `Dictionary` where `ABC123` et al will be the keys – Ňɏssa Pøngjǣrdenlarp Jan 11 '18 at 22:59
  • 2
    Adding to @Plutonix suggestion (which is correct), once converted you can select all the values of the dictionary into your array. – Nkosi Jan 11 '18 at 23:00
  • https://stackoverflow.com/q/20727787/1070452 and [15,000 similar posts here](https://www.google.com/search?q=Deserialize+/+Convert+JSON+Objects+to+dictionary+in+C%23+site:stackoverflow.com&rlz=1C1CHFX_enUS460US460&sa=X&ved=0ahUKEwinmMXjgdHYAhUG7IMKHf9DB5AQrQIIMigEMAA&biw=1062&bih=702) – Ňɏssa Pøngjǣrdenlarp Jan 11 '18 at 23:00
  • 1
    Yes, thank you @Plutonix that worked perfectly. In my class I mapped this array of objects to public Dictionary Persons { get; set; } and now everything works as expected. – cobblestone Jan 11 '18 at 23:39

0 Answers0