🙄

【Unity C#】RootがArrayのJsonをParseする

2024/08/22に公開

インポート

JsonUtilityHelper.csを作成し、以下のコードをコピペして保存します。

JsonUtilityHelper.cs
public static class JsonUtilityHelper
{
    public static T[] FromJsonArray<T>(string json)
    {
        string wrappedJson = "{\"array\":" + json + "}";
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(wrappedJson);
        return wrapper.array;
    }

    public static T FromJson<T>(string json)
    {
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.root;
    }

    [System.Serializable]
    private class Wrapper<T>
    {
        public T[] array;
        public T root;
    }
}

使い方

[
    {
        "name": "Alice,
        "age": 20,
        "isEmployed": true
    },
    {
        "name": "John,
        "age": 21,
        "isEmployed": false
    }
]
[System.Serializable]
public class Person
{
    public string name;
    public int age;
    public bool isEmployed;
}

public class Test : MonoBehaviour
{
    void Start()
    {
        string jsonString = "[{\"name\":\"Alice\",\"age\":20,\"isEmployed\":true},{\"name\":\"John\",\"age\":21,\"isEmployed\":false}]";
        Person[] array = JsonUtilityHelper.FromJsonArray<Person>(jsonString);

        Debug.Log("Name: " + array[0].name);
        Debug.Log("Age: " + array[0].age);
        Debug.Log("Is Employed: " + array[0].isEmployed);
    }
}

Discussion