0

So, here is my Json String that I want to tried to parse into array in my Unity code

[
{"id":1,"museum":"Museum Kelvin"}
,{"id":2,"museum":"Museum Keke"},
{"id":3,"museum":"Museum Keke2"},
{"id":4,"museum":"Museum Keke2"}
]

I already get the value of this string by using this code

 IEnumerator GetPertanyaan()
    {
        string getPertanyaanUrl = "http://museumadv.azurewebsites.net/museum/list";
        using (UnityWebRequest www = UnityWebRequest.Post(getPertanyaanUrl,"1"))
        {
            //www.chunkedTransfer = false;
            yield return www.Send();
            if (www.isError || www.responseCode==500 || www.responseCode==404)
            {
                Debug.Log(www.responseCode);
            }
            else
            {
                if (www.isDone)
                {
                    string jsonResult =System.Text.Encoding.UTF8.GetString(www.downloadHandler.data);
                    Debug.Log(jsonResult); // Succes to read the JSON 


                    JMuseum[] entities = JsonHelper.getJsonArray<JMuseum>(jsonResult);


                    foreach (var pert in entities)
                    {
                        Debug.Log(pert.museum); //always null
                    }

                }

            }
        }
    }

The Json Helper Class

public class JsonHelper
{
    public static T[] getJsonArray<T>(string json)
    {
        string newJson = "{ \"array\": " + json + "}";
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(newJson);
        return wrapper.array;
    }

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

and my model class for JMuseum

[System.Serializable]
public class JMuseum
{
    public int id { get; set; }
    public string museum { get; set; }
}

the problem is, the value of the museum always empty (null), but the length of the array is correct.

Do you guys have any solution to this?

Thanks,

1 Answers1

1

Unity can not serialize properties.

Try this

public class JMuseum
{
    public int id;
    public string museum;
}
Fredrik Widerberg
  • 3,068
  • 10
  • 30
  • 42