- Home /
Deserialize TexturePacker JSON at run time
Hey all,
I'm trying to deserialize the texturepacker unity json at run time but I'm confused about how to get JsonUtility to handle the file properly.
Here's an example of my json :
{"frames": {
"circle copy 2.png":
{
"frame": {"x":132,"y":1,"w":128,"h":128},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":128,"h":128},
"sourceSize": {"w":128,"h":128}
},
"circle copy 3.png":
{
"frame": {"x":262,"y":1,"w":128,"h":128},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":128,"h":128},
"sourceSize": {"w":128,"h":128}
}}
As you can see there's a frames object and then a bunch of uniquely named objects that aren't in an array. As far as I know with Unity's JsonUtility I need to know the name of the object to parse it. My google-fu isn't helping me figure out this issue.
Any direction would be appreciated.
Answer by Neamtzu · Jan 19, 2018 at 03:13 PM
Basically you'll have to create a class that is matching the data you receive in the json. Bellow you can find such an implementation, but I didn't had the chance to test it (you can see logic behind it though)
public class SizeData {
public int x;
public int y;
public int w;
public int h;
}
public class SourceSizeData {
public int w;
public int h;
}
public class ImageData {
public SizeData frame;
public bool rotated;
public bool trimmed;
public SizeData spriteSourceSize;
publoc SourceSizeData sourceSize;
}
public class Frames {
public List<ImageData> frames;
}
//decode
Frames decodedFrames = JsonUtility.FromJson<Frames>("yourJson");
Thanks for the reply. That is almost have I have already but I keep getting this error : Unexpected node type. UnityEngine.JsonUtility:FromJson(String)
I thought it may have any something to do with the way the children objects are named.
Answer by Bunny83 · Jan 19, 2018 at 05:13 PM
Unity's JsonUtility is just an object mapper so it can't be used here. You have to use a general purpose Json parser like my SimpleJSON for example ^^.
ps: There's also a Unity specific extension file for SimpleJSON. It adds some conversion helpers for most built-in Unity types. Unfortunately the serialization format i've choosen for Rect is {"x":0, "y":0, "width":128, "height":128 }
. However you can of course alter your copy anyway you like ^^ (Specifically line 276 as well as line 292 / 293).