Lucas Burns
Lucas Burns

Reputation: 429

Deserializing JSON array with Unity JsonUtility fails to get serialized values

I'm trying to deserialize card information from a JSON to be used in a Unity game, but it's not working quite right. I've tested the classes I'm trying to deserialize to, and I can manually create objects for them, but the deserializer doesn't create them correctly.

When I run the deserializing logic, the resulting array is the correct size, but none of the Cost or Name fields of the cards fill in and I'm left with an array of uninitialized Card objects.

The relevant code I have is as follows:

The file where we deserialize, Game.cs:

using System.IO;
using UnityEngine;
public class Game {

    private CardsCollection allCards;    

    private void LoadJson()
    {
        ...
        // Find the path to our JSON file
        // Save the path as "path"

        // I have verified this line gets the correct json data as a string
        string json = File.ReadAllText(path); 

        // Convert the json string into a deserialized array of objects
        // using the CardsCollection wrapper
        allCards = JsonUtility.FromJson<CardsCollection>(json);
    }

}

The Card object file, Card.cs:

using System;
[Serializable]
public class Card
{
    public string Name { get; set; }
    public int Cost    { get; set; }

    public Card(string Name, int Cost)
    {
        this.Name = Name;
        this.Cost = Cost;
    }
}

[Serializable]
public class CardsCollection
{
    public Card[] cards;
}

And finally the JSON itself:

{
    "cards": [
        {
            "Name": "copper",
            "Cost": 0
        },
        {
            "Name": "silver",
            "Cost": 3
        },
        {
            "Name": "gold",
            "Cost": 6
        },
        {
            "Name": "curse",
            "Cost": 0
        },
        {
            "Name": "estate",
            "Cost": 2
        },
        {
            "Name": "duchy",
            "Cost": 5
        },
        {
            "Name": "province",
            "Cost": 8
        }
    ]
}

Upvotes: 4

Views: 941

Answers (1)

Kieran
Kieran

Reputation: 224

The Json serialization can only handle fields (see supported types https://docs.unity3d.com/Manual/JSONSerialization.html) but your Name and Cost look like properties What is the difference between a field and a property?

Since they are marked public and can be accessed directly anyway I would just remove the {get; set}

Upvotes: 2

Related Questions