Replicating a JSON file in C#

How about something like this…

First I created classes for each of the inner bits of your structure:

public class RegionAttributes
{
    public string Animal { get; set; }
}

public class ShapeAttributes
{
    public string name { get; set; }
    public List<int> all_points_x { get; set; }
    public List<int> all_points_y { get; set; }
}

public class Region
{
    public ShapeAttributes shape_attributes { get; set; }
    public RegionAttributes region_attributes { get; set; }
}

public class Thing
{
    public string filename { get; set; }
    public int size { get; set; }
    public List<Region> regions { get; set; }
    public dynamic file_attributes { get; set; }
}

You should be able to see that the hierarchy of these classes matches the hierarchy of your JSON.

Then I initialize one of these Things:

var thing = new Dictionary<string, Thing>
{
    {
        "Dog.png173732", new Thing
        {
            filename = "Dog.png",
            size = 173732,
            regions = new List<Region>
            {
                new Region
                {
                    shape_attributes = new ShapeAttributes
                    {
                        name = "polygon",
                        all_points_x = new List<int> {189, 192, 229, 230},
                        all_points_y = new List<int> {2, 148, 148, 2},
                    },
                    region_attributes = new RegionAttributes
                    {
                        Animal = "dog",
                    }
                }
            },
            file_attributes = new object()
        }
    }
};

Again, you can see the similarity of the structure in the code to the structure of the JSON. Finally, I do this (using the Newtonsoft JSON package):

var result = JsonConvert.SerializeObject(thing, Formatting.Indented);

This results in this string:

{
  "Dog.png173732": {
    "filename": "Dog.png",
    "size": 173732,
    "regions": [
      {
        "shape_attributes": {
          "name": "polygon",
          "all_points_x": [
            189,
            192,
            229,
            230
          ],
          "all_points_y": [
            2,
            148,
            148,
            2
          ]
        },
        "region_attributes": {
          "Animal": "dog"
        }
      }
    ],
    "file_attributes": {}
  }
}

I think that’s a match. You’ll probably want to use attributes to get C#-ish names in the C# code and JSON-ish names in the JSON output. But, there you go…

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top