0

I receive a JSON array from my server onto my unity game client. The array contains different kind of gameobjects, in other words there are different types of objects in one array.

 {someArrayOfDifferentObjects:[{name:"bla", element:"ITEM"},{name:"blu",element:"ITEM"},{name:"blu",health:0, element:"ENEMY"}]}

What I try to accomplish is getting the right object type for the target object in a for loop:

private IEnumerator WaitForRequest(WWW www)
{
    yield return www;

    ResponseObject gameObjects= JsonUtility.FromJson<ResponseObject >(www.text); // from server
    object[] base = gameObjects.someArrayOfDifferentObjects;
    foreach (object obj in base )
    {
    ParentObject parent = (ParentObject ) obj;
    if (parent.element == "ITEM")
    {
    Item item = obj as Item; // throws NullReferenceException: Object reference not set to an instance of an object
    } else { // other elements}
    }
}

    {
     [Serializable]
        public class ParentObject
        {
          public string element;
        }
    }

 {
     [Serializable]
        public class Item : ParentObject
        {
          public string name;

        }
    }

It tried a couple of things and searched for a solution on the internet, but couldn't find anything that worked with c# in unity. I know this problem can't be too complicated but I'm kind of stuck at the moment.

Can anybode give me a quick hint into the right direction?

greetings,

Codehai

Codehai
  • 524
  • 1
  • 7
  • 27
  • Paste your json [here](http://json2csharp.com/) and you will get the proper classes for it. Remove all the `{ get; set; }` and make sure to add `[Serializable]` to generated each class. Now you can do `RootObject obj = JsonUtility.FromJson(www.text);`. – Programmer Jul 02 '17 at 20:50
  • Please avoid using `gameObjects` as your variable name. You will likely run into problems with that. – Programmer Jul 02 '17 at 20:50
  • Hello, thanks for your answer. I changed the names to give a minimal examle. I looked at the duplicate you suggested but it assumes that all the objects inside the array are of the same type. In my case the array contains different objects with different fields. How to handle that case? – Codehai Jul 02 '17 at 20:52
  • 1
    You can't with `JsonUtility`. Use `SimpleJSON`. It can be used for that to convert to any object. It is linked on the duplicated answer too. – Programmer Jul 02 '17 at 21:12

0 Answers0