Search Unity

Problems reading Json

Discussion in 'Editor & General Support' started by Dazzid, Jul 26, 2016.

  1. Dazzid

    Dazzid

    Joined:
    Apr 15, 2014
    Posts:
    61
    Hi,
    I need help with Json on Unity. The documentation is not quite clear.
    Im trying with something like this but not result:
    My json is like this
    {"1":{"info":"AREAS 1, 2 & 3\n(Primary somatosensory cortex - Postcentral gyrus)”},{“2”:{“info":"AREAS 1, 2 & 3\n(Primary somatosensory cortex - Postcentral gyrus)”},…
    by 50 objects
    Code (CSharp):
    1. public class myData{
    2.         public string brodmannInfo;
    3.     }
    Code (CSharp):
    1.     void Start () {
    2.         using (StreamReader r = new StreamReader("./Data/offLineVersion/Brodamnn_areas_database"))
    3.         {
    4.             string json = r.ReadToEnd();
    5.             myData thisData = JsonUtility.FromJson<myData>(json);
    6.             Debug.Log (thisData.brodmannInfo);
    7.         }
    8.  
    9.         //myData thisData = JsonUtility.FromJson<myData> (jsonFile.text);
    10.     }
    11.    
     
  2. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,659
    The name of your field in your C# type definition ('brodmannInfo') needs to match the name of the field in your JSON ('info').

    However, be aware that Unity doesn't currently have built-in support for loading 'dictionary-style' JSON - i.e. to load your fifty different "1", "2", "3" etc keys and their values, you'll have to actually have variables called "1", "2", "3", and so on, in your data type. If you have control over the input format I recommend using an array instead of a dictionary like this...
     
  3. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,659
    As a tip, one thing you can do when debugging this stuff is to set up some test data from code, and use ToJson to convert it to a string, and look at the result. That should show you the format that Unity is expecting the input to be in.
     
  4. greg-harding

    greg-harding

    Joined:
    Apr 11, 2013
    Posts:
    524
    We're currently using other parsers because of this. Are there plans to support dictionaries... or does this rely on Mono/C#/.Net profile upgrades or other general serialisation stuff?
     
  5. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,659
    It requires changes to the serialisation system in general. I've already done some initial refactoring to prepare for it, but it's going to take a while.
     
  6. greg-harding

    greg-harding

    Joined:
    Apr 11, 2013
    Posts:
    524
    Thanks for the update. Have some more bacon :)