Невозможно десериализовать текущий объект JSON (например, {"name": "value"}) в тип 'Value []', поскольку для типа требуется массив JSON (например, [1,2,3]) - PullRequest
2 голосов
/ 22 марта 2020

Я борюсь с этим исключением. Я пытаюсь получить некоторую информацию из файла json и извлечь из него объект C#. Но по некоторым причинам Unity не позволяет мне десериализовать его.

Вот мой C# код:

IEnumerator SendRequest(string urlParam, Action<UnityWebRequest> callback)
    {
        using (webRequest = UnityWebRequest.Get(urlParam))
        {
            yield return webRequest.SendWebRequest();
            callback(webRequest);

            if (webRequest.isNetworkError || webRequest.isHttpError)
                Debug.LogError(webRequest.error);
            //else Debug.Log("Command has been performed successfully");
        }
    }

public void StartTestSuite2()
    {
        StartCoroutine(SendRequest("http://localhost:8086/down|PopOut1", (UnityWebRequest req) =>
        {
            if (req.isNetworkError || req.isHttpError)
            {
                Debug.Log($"{req.error}: {req.downloadHandler.text}");
            }
            else
            {
                Value[] values = JsonConvert.DeserializeObject<Value[]>(req.downloadHandler.text);

                foreach (Value value in values)
                {
                    Debug.Log(value.x);
                }
            }
        }));
    }

Я уже нашел его в Google и обнаружил, что у некоторых людей возникла та же проблема но я не могу понять, как решить мою проблему здесь. Я попытался десериализовать Value вместо Value[], и это действительно работает.

Но тогда я не могу go через мой стол с foreach (который мне нужен)

Кто-нибудь может мне помочь ? Спасибо,

РЕДАКТИРОВАТЬ: Вот мои типы "Value":

public class Value
{
    public string name;
    public string type;
    public float x;
    public float y;
    public int instanceID;
}

А вот мой json файл:

{
    "scene": "UI",
    "gameObjectDefinitions": [{
        "name": "Image",
        "type": "UnityEngine.RectTransform",
        "x": 314.79595947265627,
        "y": 327.6845397949219,
        "instanceID": 28548,
        "buttons": [],
        "children": []
    }, {
        "name": "TopFade",
        "type": "UnityEngine.RectTransform",
        "x": 26.790924072265626,
        "y": 326.97796630859377,
        "instanceID": 28614,
        "buttons": ["TopFade (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 26.790924072265626,
            "y": 326.97796630859377,
            "instanceID": 28342,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "Button (1)",
        "type": "UnityEngine.RectTransform",
        "x": 81.19093322753906,
        "y": 327.207763671875,
        "instanceID": 28600,
        "buttons": ["Button (1) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 81.19093322753906,
            "y": 327.207763671875,
            "instanceID": 28792,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "Button (2)",
        "type": "UnityEngine.RectTransform",
        "x": 135.5909423828125,
        "y": 327.207763671875,
        "instanceID": 28506,
        "buttons": ["Button (2) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 135.5909423828125,
            "y": 327.207763671875,
            "instanceID": 28576,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "Button (3)",
        "type": "UnityEngine.RectTransform",
        "x": 602.7999877929688,
        "y": 327.207763671875,
        "instanceID": 28628,
        "buttons": ["Button (3) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 602.7999877929688,
            "y": 327.207763671875,
            "instanceID": 28450,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "Button (4)",
        "type": "UnityEngine.RectTransform",
        "x": 548.4000244140625,
        "y": 327.207763671875,
        "instanceID": 28520,
        "buttons": ["Button (4) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 548.4000244140625,
            "y": 327.207763671875,
            "instanceID": 28540,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "Button1Panel",
        "type": "UnityEngine.RectTransform",
        "x": 26.808990478515626,
        "y": 287.9584045410156,
        "instanceID": 28724,
        "buttons": [],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 26.808990478515626,
            "y": 287.9584045410156,
            "instanceID": 28662,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "Button2Panel",
        "type": "UnityEngine.RectTransform",
        "x": 81.17160034179688,
        "y": 287.9584045410156,
        "instanceID": 28742,
        "buttons": [],
        "children": [{
            "name": "Text (1)",
            "type": "UnityEngine.RectTransform",
            "x": 81.17160034179688,
            "y": 287.9584045410156,
            "instanceID": 28372,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "Button3Panel",
        "type": "UnityEngine.RectTransform",
        "x": 135.55799865722657,
        "y": 287.9584045410156,
        "instanceID": 28332,
        "buttons": [],
        "children": [{
            "name": "Text (2)",
            "type": "UnityEngine.RectTransform",
            "x": 135.55799865722657,
            "y": 287.9584045410156,
            "instanceID": 28476,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "PopOutMaster",
        "type": "UnityEngine.RectTransform",
        "x": 835.2000122070313,
        "y": 198.75999450683595,
        "instanceID": 28776,
        "buttons": [],
        "children": [{
            "name": "PopOut1",
            "type": "UnityEngine.RectTransform",
            "x": 684.739990234375,
            "y": 198.75999450683595,
            "instanceID": 28310,
            "buttons": ["PopOut1 (UnityEngine.UI.Button)"],
            "children": [{
                "name": "Text",
                "type": "UnityEngine.RectTransform",
                "x": 583.5560302734375,
                "y": 198.75999450683595,
                "instanceID": 28784,
                "buttons": [],
                "children": []
            }]
        }]
    }, {
        "name": "PopOutMaster (1)",
        "type": "UnityEngine.RectTransform",
        "x": 835.2000122070313,
        "y": 135.52000427246095,
        "instanceID": 28834,
        "buttons": [],
        "children": [{
            "name": "PopOut2",
            "type": "UnityEngine.RectTransform",
            "x": 719.0799560546875,
            "y": 135.52000427246095,
            "instanceID": 28492,
            "buttons": ["PopOut2 (UnityEngine.UI.Button)"],
            "children": [{
                "name": "Text",
                "type": "UnityEngine.RectTransform",
                "x": 617.89599609375,
                "y": 135.52000427246095,
                "instanceID": 28324,
                "buttons": [],
                "children": []
            }]
        }]
    }, {
        "name": "PopOutMaster (2)",
        "type": "UnityEngine.RectTransform",
        "x": 835.2000122070313,
        "y": 72.27999877929688,
        "instanceID": 28716,
        "buttons": [],
        "children": [{
            "name": "PopOut3",
            "type": "UnityEngine.RectTransform",
            "x": 719.0799560546875,
            "y": 72.27999877929688,
            "instanceID": 28800,
            "buttons": ["PopOut3 (UnityEngine.UI.Button)"],
            "children": [{
                "name": "Text",
                "type": "UnityEngine.RectTransform",
                "x": 617.89599609375,
                "y": 72.27999877929688,
                "instanceID": 28442,
                "buttons": [],
                "children": []
            }]
        }]
    }, {
        "name": "BottomFade",
        "type": "UnityEngine.RectTransform",
        "x": 314.79595947265627,
        "y": 12.919998168945313,
        "instanceID": 28592,
        "buttons": [],
        "children": []
    }, {
        "name": "B4",
        "type": "UnityEngine.RectTransform",
        "x": 27.20001220703125,
        "y": 12.919998168945313,
        "instanceID": 28408,
        "buttons": ["B4 (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 27.20001220703125,
            "y": 12.919998168945313,
            "instanceID": 28690,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "ButtonSmall (1)",
        "type": "UnityEngine.RectTransform",
        "x": 81.60000610351563,
        "y": 12.919998168945313,
        "instanceID": 28698,
        "buttons": ["ButtonSmall (1) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 81.60000610351563,
            "y": 12.919998168945313,
            "instanceID": 28484,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "ButtonSmall (2)",
        "type": "UnityEngine.RectTransform",
        "x": 136.0,
        "y": 12.919998168945313,
        "instanceID": 28380,
        "buttons": ["ButtonSmall (2) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 136.0,
            "y": 12.919998168945313,
            "instanceID": 28734,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "ButtonSmall (3)",
        "type": "UnityEngine.RectTransform",
        "x": 190.39999389648438,
        "y": 12.919998168945313,
        "instanceID": 28650,
        "buttons": ["ButtonSmall (3) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 190.39999389648438,
            "y": 12.919998168945313,
            "instanceID": 28568,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "ButtonSmall (4)",
        "type": "UnityEngine.RectTransform",
        "x": 244.8000030517578,
        "y": 12.919998168945313,
        "instanceID": 28556,
        "buttons": ["ButtonSmall (4) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 244.8000030517578,
            "y": 12.919998168945313,
            "instanceID": 28842,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "ButtonSmall (5)",
        "type": "UnityEngine.RectTransform",
        "x": 299.20001220703127,
        "y": 12.919998168945313,
        "instanceID": 28678,
        "buttons": ["ButtonSmall (5) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 299.20001220703127,
            "y": 12.919998168945313,
            "instanceID": 28814,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "ButtonSmall (6)",
        "type": "UnityEngine.RectTransform",
        "x": 353.6000061035156,
        "y": 12.919998168945313,
        "instanceID": 28822,
        "buttons": ["ButtonSmall (6) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 353.6000061035156,
            "y": 12.919998168945313,
            "instanceID": 28670,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "Button (5)",
        "type": "UnityEngine.RectTransform",
        "x": 235.2109375,
        "y": 327.4600830078125,
        "instanceID": 28764,
        "buttons": ["Button (5) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 235.2109375,
            "y": 327.4600830078125,
            "instanceID": 28400,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "Button (6)",
        "type": "UnityEngine.RectTransform",
        "x": 280.5690612792969,
        "y": 327.4600830078125,
        "instanceID": 28752,
        "buttons": ["Button (6) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 280.5690612792969,
            "y": 327.4600830078125,
            "instanceID": 28468,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "Button (7)",
        "type": "UnityEngine.RectTransform",
        "x": 325.9245300292969,
        "y": 327.4600830078125,
        "instanceID": 28430,
        "buttons": ["Button (7) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 325.9245300292969,
            "y": 327.4600830078125,
            "instanceID": 28392,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "Button (8)",
        "type": "UnityEngine.RectTransform",
        "x": 371.2799987792969,
        "y": 327.4600830078125,
        "instanceID": 28360,
        "buttons": ["Button (8) (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 371.2799987792969,
            "y": 327.4600830078125,
            "instanceID": 28532,
            "buttons": [],
            "children": []
        }]
    }, {
        "name": "START",
        "type": "UnityEngine.RectTransform",
        "x": 309.55999755859377,
        "y": 177.0,
        "instanceID": 28350,
        "buttons": ["START (UnityEngine.UI.Button)"],
        "children": [{
            "name": "Text",
            "type": "UnityEngine.RectTransform",
            "x": 309.55999755859377,
            "y": 177.0,
            "instanceID": 28584,
            "buttons": [],
            "children": []
        }]
    }],
    "buttons": ["TopFade (UnityEngine.UI.Button)", "Button (1) (UnityEngine.UI.Button)", "Button (2) (UnityEngine.UI.Button)", "Button (3) (UnityEngine.UI.Button)", "Button (4) (UnityEngine.UI.Button)", "PopOut1 (UnityEngine.UI.Button)", "PopOut2 (UnityEngine.UI.Button)", "PopOut3 (UnityEngine.UI.Button)", "B4 (UnityEngine.UI.Button)", "ButtonSmall (1) (UnityEngine.UI.Button)", "ButtonSmall (2) (UnityEngine.UI.Button)", "ButtonSmall (3) (UnityEngine.UI.Button)", "ButtonSmall (4) (UnityEngine.UI.Button)", "ButtonSmall (5) (UnityEngine.UI.Button)", "ButtonSmall (6) (UnityEngine.UI.Button)", "Button (5) (UnityEngine.UI.Button)", "Button (6) (UnityEngine.UI.Button)", "Button (7) (UnityEngine.UI.Button)", "Button (8) (UnityEngine.UI.Button)", "START (UnityEngine.UI.Button)"]
}

1 Ответ

1 голос
/ 22 марта 2020

Теперь, когда вы опубликовали оставшуюся часть JSON, я вижу, что вы пытаетесь получить доступ к внутреннему массиву, заключенному в более крупный объект JSON.

Сам код "работал" с одним Value, потому что у вас есть один JSON объект, без массива!

Однако, он не будет иметь соответствующих полей записи в строке JSON, чтобы они в любом случае имели свои значения по умолчанию.


Так что, скорее всего, вы должны иметь именно тот класс-обертку, который включает в себя соответствующие поля вашего JSON

[Serializable]
public class JsonRoot
{
    public string scene;
    public Value[] gameObjectDefinitions;
}

, затем десериализовать в этот тип

var jsonRoot = JsonConverter.Deserialize<JsonRoot>(req.downloadHandler.text);

, и теперь вы можете получить доступ к итерации по

foreach(var value in jsonRoot.gameObjectDefinitions)
{
    ...
}

Альтернативой здесь может быть использование SimpleJson

var jsonRoot = JSON.Parse(req.downloadHandler.text);
var values = jsonRoot["gameObjectDefinitions"].AsArray;

К вашему комментарию относительно children:

В классе Value вы найдете, что их просто не существует, поэтому в настоящее время там нет способа получить к ним доступ.

Если вы хотите представить полный формат JSON, ваши классы должны выглядеть следующим образом:

[Serializable]
public class JsonRoot
{
    public string scene;
    public Value[] gameObjectDefinitions;
    public string[] buttons;
}

[Serializable]
public class Value
{
    public string name;
    public string type;
    public float x;
    public float y;
    public int instanceID;

    public string[] buttons;
    public Value[] children;
}

Примечание : Unity ограничивает сериализацию таких структур рекурсивного типа до максимального уровня гнезда 7! Я не знаю, как библиотека JSON, которую вы используете, справляется с этим, но помните, что это ограничение может существовать.

Я не знаю, какова ваша конечная цель, но я думаю, что единственный способ итерации все дети и дочерние элементы действительно будут рекурсивным методом, например

...

foreach(var value in jsonRoot.gameObjectDefinitions)
{
    HandleValue(value);
}

...

private void HandleValue(Value value)
{
    ...

    if(value.children != null)
    {
        foreach(var child in value.children)
        {
            HandleValue(child);
        }
    }
}
...