I’m working with unity, and I’m trying to read a json file exported from tiled. So everything was fine until I came across the “tiles” within a tileset.
So the json looks like this:
As you can see, the property “tiles” is not a list of tiles, it is instead an object with some properties inside, like “0”, “1”, etc. I was expecting it to be something like:
Is that intended? How am I gonna be able to parse that? I am using the built-in JsonUtility class in unity.
Tile indices are not guaranteed to be consecutive, so even if it was a list, you’d have to iterate it to find each tile by its ID. However, a list may still have been better because the tile IDs have to be converted to strings the way they are stored now, since JSON only allows strings as keys. Of course, changing it now would break everyone’s JSON map reader, so it’s something to reconsider later.
While loading this file, you’ll get the
tiles property as JSON object. You could iterate all its key/value pairs and write it to some more optimal data structure, converting the keys to integer tile IDs. That is what Tiled does when it loads a JSON tileset.
Thanks for the answer! How do I iterate through key/value pairs of that object?
That depends entirely on the JSON API you’re using.
Oh, I’m using the unity’s built-in json api that is very simple and probably doesn’t have this feature:
What json api could I use then? Or is there another way to do this?
Hmm, right, that JSON API looks like a rather high-level convenience thing and you will need to look at a lower-level JSON reader. Maybe try Json.NET.
Thanks. I managed to make it work using Json.NET.
Actually Json.NET doesn’t work in unity, so I used a branch of Json.NET modified to work with unity, following this tutorial:
After installing that, in my target class, I treated this tiles as a dictionary, like this:
public Dictionary<string, TileData> tiles;
And now it magically works.
The only problem is that they say this unity.Json.NET doesn’t work with iOS, but I think I’m gonna have to deal with that in the future if I ever want to make a build for iOS =(