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.

5
  • Would a dictionary work for you? Commented Nov 2, 2020 at 7:54
  • this should help you Commented Nov 2, 2020 at 7: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. Commented Nov 2, 2020 at 8:11
  • 1
    Neither POCO nor Json can be changed. Commented Nov 2, 2020 at 8:14
  • That's an important part for an answer. I added it to the question for you. Commented Nov 2, 2020 at 8:23

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

... and then you'd match the _ids to your POCO's Properties ... not beautiful, but should work. @OP
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.