Morpheus Morpheus - 4 months ago 9
JSON Question

Defining a dictionary in a C# class

I have a .json file which i want to read in C#.

The Json File looks like this:

{"SN0124":{
"category1": 0,
"output": {
"ABC": [],
"DEF": 0,
"GHI": "ABDEF"
},
"category2": 0,
"category3": 0
},
"SN0123":{
"category1": 0,
"output": {
"ABC": ["N1", "N2"],
"DEF": 0,
"GHI": "ABDEF"
},
"category2": 0,
"category3": 0
}


Initially the output field was absent and my custom class for reading the Json file is as follows:

namespace Server.Models
{
public class Pets
{
public string category1 { get; set; }
public string category2 { get; set; }
public string category3 { get; set; }

}
}


The output was recently added and I am not sure how to include that dictionary in the class file so that I can read the json file. Any help will be greatly appreciated.

thanks!

Answer

This should work fine. I have basically created a new class called Output that contains the expected JSON fields. I have also edited the type of the category fields to int.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string JSONInput = @"{""SN0124"": {
                                    ""category1"": 0,
                                    ""output"": {
                                        ""ABC"": [], 
                                        ""DEF"": 0, 
                                        ""GHI"": ""ABDEF""
                                    },
                                    ""category2"": 0, 
                                    ""category3"": 0
                                },
                                ""SN0123"": {
                                    ""category1"": 0, 
                                    ""output"": {
                                        ""ABC"": [""N1"", ""N2""], 
                                        ""DEF"": 0, 
                                        ""GHI"": ""ABDEF""
                                    },
                                    ""category2"": 0, 
                                    ""category3"": 0
                                }}";
            Dictionary<string, Pets> deserializedProduct = JsonConvert.DeserializeObject<Dictionary<string, Pets>>(JSONInput);
            Console.ReadKey();
        }
    }

    public class Output
    {
        public string[] ABC { get; set; }
        public int DEF { get; set; }
        public string GHI { get; set; }
    }

    public class Pets
    {

        public int category1 { get; set; }

        public Output output { get; set; }

        public int category2 { get; set; }
        public int category3 { get; set; }

    }
}
Comments