底辺SE奮闘記

年収300万SEブログ

【Unity】JSON must represent an object type. への対応

UnityのUnityEngine.JsonUtilityはJsonパースにおいて非常に有用ですが、少し癖が強い感があります。

よくありそうなケース

[
    {
        "id":1,
        "name":"山田"
    },
    {
        "id":2,
        "name":"田中"
    }
]

これがパースできないのです。

これをパースしようとすると、

JSON must represent an object type. 

と出てエラーとなります。

パースできるようにする場合には下記のように変更が必要です。

{
    "persons":[
        {
            "id":1,
            "name":"山田"
        },
        {
            "id":2,
            "name":"田中"
        }
    ]
}

パースするコードは例えばこんな感じ、

using System;
using UnityEngine;

public class MainClass {
    public void main ()
    {
        var jsonStr = "さっきのいい感じのJSON";
        var persons = JsonUtility.FromJson<Persons>(jsonStr);
    }
}

[Serializable]
public class Person{
    public int id;
    public string name;
}

[Serializable]
public class Persons{
    public Person[] persons;
}