Search code examples
c#jsontiled

C# Turn JSON Into Data


I'm using a program (Tiled) to create tilesets for a game, which spits out JSON files similar to this:

http://pastebin.com/t7UHzG7w

And i'm looking to turn it into data that I can use (a map of the "data", or an int[][] of the "data", as well as the width/height, all the other info is extraneous and I know already), and don't really know how to go about it.

How do I go from that JSON to data in a format I can deal with it?


Solution

  • You should use create a model class to represent the JSON data you have. Then you can use JavaScriptSerializer or Newsoft JOSN library to convert this data into object.

    You should create model class for your data:

    public class Layer
    {
        public List<int> data { get; set; }
        public int height { get; set; }
        public string name { get; set; }
        public int opacity { get; set; }
        public string type { get; set; }
        public bool visible { get; set; }
        public int width { get; set; }
        public int x { get; set; }
        public int y { get; set; }
    }
    
    public class Tileset
    {
        public int columns { get; set; }
        public int firstgid { get; set; }
        public string image { get; set; }
        public int imageheight { get; set; }
        public int imagewidth { get; set; }
        public int margin { get; set; }
        public string name { get; set; }
        public int spacing { get; set; }
        public int tilecount { get; set; }
        public int tileheight { get; set; }
        public int tilewidth { get; set; }
    }
    
    public class Data
    {
        public int height { get; set; }
        public List<Layer> layers { get; set; }
        public int nextobjectid { get; set; }
        public string orientation { get; set; }
        public string renderorder { get; set; }
        public int tileheight { get; set; }
        public List<Tileset> tilesets { get; set; }
        public int tilewidth { get; set; }
        public int version { get; set; }
        public int width { get; set; }
    }
    

    Once this is done, you can use Newtonsoft.Json library to parse the string data into this object.

    string text = "<Your Json data>";
    var result = JsonConvert.DeserializeObject<Data>(text);
    

    You can download Newtonsoft JSON library from here:

    http://www.newtonsoft.com/json

    Or use NPM as well:

    Install-Package Newtonsoft.Json