+2 votes

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>;


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


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

in Engine by (134 points)

2 Answers

0 votes

The json parse result is not a generic Dictionary, use

jsonFile as Dictionary

instead of

jsonFile as Dictionary<object, object>

and it will wrok.

by (150 points)
0 votes

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);
by (14 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.