Parsing a JSON file in c# (Unity)

Viewed 931

I'm trying to parse a JSON file that I created from a JS app into Unity, in C#.

I have no experience with Json or reading data in general so I'm sure I'm missing something basic.

Here is how the data structure looks like in JS:

function DialIn () {
    this.id = null; this.line = "default in line"; this.links = [];
}

function DialOut () {
    this.id = null; this.line = "defauLt out line"; this.links = []; this.autoDelete = false;
}

function DialNode () {
    this.id = null; this.posX = null; this.posY = null; this.ins = []; this.outs = [];
}
            
var NodesDB = []; //DataBase of dial nodes

In a nutshell, NodesDB is an array of DialNode and each DialNode contains an array of ins and an array of outs.

Once store in a JSON, it looks like something like this (for example, with 3 nodes in NodesDB)

[{"id":"dn0","posX":82,"posY":234,"ins":[{"id":"dn0_in_0","line":"This is dynamic Blep ?","links":[]}],"outs":[{"id":"dn0_out_0","line":"Coucou, this is a reply.","links":["dn1_in_0"],"autoDelete":false}]},{"id":"dn1","posX":520,"posY":171,"ins":[{"id":"dn1_in_0","line":"This is dynamic Blep ?","links":["dn0_out_0"]}],"outs":[{"id":"dn1_out_0","line":"Coucou, this is a reply.","links":[],"autoDelete":false},{"id":"dn1_out_1","line":"Coucou, this is a reply.","links":["dn2_in_0"],"autoDelete":false}]},{"id":"dn2","posX":948,"posY":139,"ins":[{"id":"dn2_in_0","line":"This is dynamic Blep ?","links":["dn1_out_1"]}],"outs":[{"id":"dn2_out_0","line":"Coucou, this is a reply.","links":[],"autoDelete":false}]}]

Then, in Unity, I created this structure, trying to mimic the structures from JS:

    [System.Serializable]
    class DialIn
    {
        string id; string line; string[] links;
    }


    [System.Serializable]
    class DialOut
    {
        string id; string line; string[] links; bool autoDelete;
    }


    [System.Serializable]
    class DialNode
    {
        string id; int posX, posY; DialIn[] ins; DialOut[] outs;
    }

    DialNode[] NodesDB;

From there, I'm using these commands:

path = Application.dataPath + "/Jsons/Bloup.json";
jsonData = File.ReadAllText(path);

And I believe I should use something like this: NodesDB = JsonUtility.FromJson<DialNode>(jsonData);

But apparently, it's not that simple.

Any help would be greatly appreciated :o

2 Answers

Make all your object's member variables public. JSONUtility doesn't (de)serialize private member variables.
See the documentation.

Alternatively if you really want your member variables private, add the [SerializeField] attribute to every field you want serialized.

you can add simple json to your project and them using on your top script, I use this Script for parse and other...

 var N = JSON.Parse(the_JSON_string);
 var versionString = N[0]["id"].Value;  
 var versionString = N[0]["posX"].Value;  

and other ....

Related