Karthik Dheeraj
Karthik Dheeraj

Reputation: 1049

How can I Convert Below JSON to C# POCO Object

[
  { "_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.

Upvotes: 1

Views: 169

Answers (2)

Athanasios Kataras
Athanasios Kataras

Reputation: 26352

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

Upvotes: 1

Salah Akbari
Salah Akbari

Reputation: 39946

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.

Upvotes: 0

Related Questions