Search Unity

Parsing json data structure

Discussion in 'Editor & General Support' started by darkanum, Dec 17, 2017.

  1. darkanum

    darkanum

    Joined:
    Dec 16, 2011
    Posts:
    7
    have to create a class that Store all the dog breeds and sub breeds using the dog api: https://dog.ceo/api/breeds/list/all

    I'm having some trouble to parse the data structure to object. Normally, i would create a class with the variable names mirroring the key and use the JsonUtility to parse. But it is not working in this case.

    Code (CSharp):
    1. public class DogAPI : MonoBehaviour {
    2.  
    3.    [SerializeField]
    4.    public JsonMessage json;
    5.  
    6.    void Start () {
    7.        StartCoroutine(LoadBreeds());
    8.    }
    9.  
    10.    public IEnumerator LoadBreeds()
    11.    {
    12.        WWW www = new WWW("https://dog.ceo/api/breeds/list/all");
    13.        yield return www;
    14.  
    15.        json = JsonUtility.FromJson<JsonMessage>(www.text);
    16.    }
    17. }
    18.  
    19.  
    20. [System.Serializable]
    21. public class JsonMessage
    22. {
    23.    public string status;
    24.    public Dictionary<string , List<string>> message;
    25. }
     
  2. fffMalzbier

    fffMalzbier

    Joined:
    Jun 14, 2011
    Posts:
    3,276
    The problem is with the Dictionary.
    Unitys JsonUtility just uses unity's standard serialisation and that does not support dictionaries.
    You may package that data in some other form and the add it to the dictionary.
    Or you can use a json parser that can work with dictionaries.