Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

json - Unity C# JsonUtility is not serializing a list

I've got some data I need to serialize/deserialize, but JsonUtility is just not doing what it's supposed to. Here's the objects I'm working with:

public class SpriteData {
    public string sprite_name;
    public Vector2 sprite_size;
    public List<Vector2> subimage;
}

public class SpriteDataCollection
{
    public SpriteData[] sprites;
}

If I create a SpriteDataCollection, and attempt to serialize it with JsonUtility, I just get an empty object {}. Here's how it's being built:

            SpriteData data = new SpriteData();
            data.sprite_name = "idle";
            data.sprite_size = new Vector2(64.0f, 64.0f);
            data.subimage = new List<Vector2> { new Vector2(0.0f, 0.0f) };

            SpriteDataCollection col = new SpriteDataCollection();
            col.sprites = new SpriteData[] { data };

            Debug.Log(JsonUtility.ToJson(col));

The debug log only prints "{}". Why isn't it serializing anything? I've tested it out, and serializing a single SpriteData does exactly what it's supposed to do, but it won't work in the SpriteDataCollection.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are 4 known possible reasons why you may get empty Json in Unity.

1.Not including [Serializable]. You get empty json if you don't include this.

2.Using property (get/set) as your variable. JsonUtility does not support this.

3.Trying to serializing a collection other than List.

4.Your json is multi array which JsonUtility does not support and needs a wrapper to work.

The problem looks like #1. You are missing [Serializable] on the the classes. You must add using System; in order to use that.

[Serializable]
public class SpriteData {
    public string sprite_name;
    public Vector2 sprite_size;
    public List<Vector2> subimage;
}

and

[Serializable]
public class SpriteDataCollection
{
    public SpriteData[] sprites;
}

5.Like the example, given above in the SpriteData class, the variable must be a public variable. If it is a private variable, add [SerializeField] at the top of it.

[Serializable]
public class SpriteDataCollection
{
    [SerializeField]
    private SpriteData[] sprites;
}

If still not working then your json is probably invalid. Read "4.TROUBLESHOOTING JsonUtility" from the answer in the "Serialize and Deserialize Json and Json Array in Unity" post. That should give you inside on how to fix this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...