1
[
  { "_id" : "BrownHair", "Count" : 1 },
  {"_id" : "BlackHair" , "Count" : 5},
  {"_id" : "WhiteHair" , "Count" : 15}
]

I would like convert above json to C# POCO Object like below

 public class HairColors
    {
        public int BrownHair { get; set; }
        public int BlackHair { get; set; }
        public int WhiteHair { get; set; }       
    }

Mind that I cannot change structures of neither POCO nor JSON.

Fildor
  • 14,510
  • 4
  • 35
  • 67
Karthik Dheeraj
  • 1,039
  • 1
  • 13
  • 25
  • Would a dictionary work for you? – Theraot Nov 02 '20 at 07:54
  • [this](https://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object) should help you – styx Nov 02 '20 at 07:55
  • 1
    What parts do you control? Can you change how the Json is structured? Can you change the way your POCO is structured? Do both _have to_ look like the way they do now? Asking because you can solve this in one of three ways: 1. Change JSON, 2. change POCO, 3. Come up with some parsing code that "translates" the slightly incompatible structures. Mind that in latter case, you might need to also have a custom serialization code. – Fildor Nov 02 '20 at 08:11
  • 1
    Neither POCO nor Json can be changed. – Karthik Dheeraj Nov 02 '20 at 08:14
  • That's an important part for an answer. I added it to the question for you. – Fildor Nov 02 '20 at 08:23

2 Answers2

1

You can do some custom parsing with JObject https://dotnetfiddle.net/ydvZ3l

        string json = "[\r\n  { \"_id\" : \"BrownHair\", \"Count\" : 1 },\r\n  {\"_id\" : \"BlackHair\" , \"Count\" : 5},\r\n  {\"_id\" : \"WhiteHair\" , \"Count\" : 15}\r\n]";

        var jobjects = JArray.Parse(json);
        foreach(var item in jobjects) {
            // Map them here
            Console.WriteLine(item["_id"]);
            Console.WriteLine(item["Count"]);
        }
// Output
//BrownHair
//1
//BlackHair
//5
//WhiteHair
15
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • 1
    ... and then you'd match the `_id`s to your POCO's Properties ... not beautiful, but should work. @OP – Fildor Nov 02 '20 at 08:18
  • 1
    Indeed! Not beautiful at all, I would much rather go with a solution like Salah is describing if I could change the classes. But I wouldn't introduce two new classes just to deserialize and the map to the object. – Athanasios Kataras Nov 02 '20 at 08:37
0

I would use something like this:

public class MyArray    {
    public string _id { get; set; } 
    public int Count { get; set; } 
}

public class Root    {
    public List<MyArray> MyArray { get; set; } 
}

The usage:

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 

The https://json2csharp.com/ will be your best friend in this case.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109