Reading from Json c#

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By AuthorSan

I would like to read dialogs from a json file:

{
 
 "1" : {
    "CharacterName" : "Niti",
    "Dialog" : "I guess this is where I'll die."
  },
  "2" :
  {
    "CharacterName" : "Niti",
    "Dialog" : "If I ever get to die, that is."
  }
}

This is the code:

  Godot.File files = new Godot.File();
    files.Open("res://MyDialog/TestDialog.json", Godot.File.ModeFlags.Read);

    string text = files.GetAsText();

 

    var jsonFile =  JSON.Parse(text).Result;

    Dictionary<object, object> ParsedData = jsonFile as Dictionary<object, object>;

    files.Close();

When I try printing json file, It the get the strings that are there in my file

        GD.Print(ParsedData["1"]);

But when I print Parsed Data, I get a null reference exception

:bust_in_silhouette: Reply From: miskotam

The json parse result is not a generic Dictionary, use

jsonFile as Dictionary

instead of

jsonFile as Dictionary<object, object>

and it will wrok.

:bust_in_silhouette: Reply From: octod

Hi, using c# you can virtually install and use any .net library.

I would suggest you to use the Newtonsoft.Json library, it’s really helpful and performs pretty well.

Let’s say you have a class Dialog

public class Dialog {
    public string CharacterName { get; set; }
    public string Dialog { get; set; }
}

You can deserialize a string like this

var casted = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, Dialog>(text);
Dialog maybedialog;
casted.TryGetValue("0", out maybedialog);
GD.Print(maybedialog.CharacterName, maybedialog.Dialog);