How to parse Rectangle data from Json file

Hello, I am trying to parse tile data from a json file which looks something like this:

[
	{
		"id": 0,
		"textureRect": {
			"x": 0,
			"y": 0,
			"width": 16,
			"height": 16
		}
	},
	{
		"id": 1,
		"textureRect": {
			"x": 16,
			"y": 0,
			"width": 16,
			"height": 16
		}
	}
]

I’m using Json.NET to do the parsing but I am unsure as to how to convert it into objects like this:

class Tile
{
	public readonly Rectangle TextureRect;

    public Tile(Rectangle textureRect)
	{
		TextureRect = textureRect;
	}
}

Any help??

Ok so I’ve made some progress. This how I do it now:

JArray array = JArray.Parse(json);

var tileObj = array[0];

Rectangle rect = new Rectangle(
	(int)tileObj["textureRect"]["x"],
	(int)tileObj["textureRect"]["y"],
	(int)tileObj["textureRect"]["width"],
	(int)tileObj["textureRect"]["height"]
);

But it feels dirty dealing with strings and casts like that. I would prefer a custom converter, might even be faster.

You can define two classes :

public class Rectangle
{
    public int id { get; set; }
    public TextureRect textureRect { get; set; }

    public static List<Rectangle> ParseFromJSON(string json)
    {
       return JsonConvert.DeserializeObject<List<Rectangle>>(json);            
    }
}

public class TextureRect
{
    public int x { get; set; }
    public int y { get; set; }
    public int width { get; set; }
    public int height { get; set; }        
}

Imports will be :

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

Then, you can call something like this :

        string json = System.IO.File.ReadAllText("json1.json");
        List<Rectangle> Rectangles = Rectangle.ParseFromJSON(json);

        Console.WriteLine("Rectangles:" + Rectangles.Count);

Your json works with this code.

Tip : Use Json .NET only if you are using .NET 4.* frameworks. Use System.Text.Json for .NET core 3 and .NET 5+

Thanks for the answer but could you elaborate a bit more on why I should switch to System.Text.Json if I’m using .Net core 3. I couldn’t find any resources online on the reason for that.

If using json.net you can create your own json converters where you tell it when it finds “rectangle” to check if it matches this type. If matches can tell it to create a rectangle from json to object or object to json (text).