Jsonconvert.Deserializeobject is not reading the value of my json. (Values returning to null)

Asked

Viewed 35 times

0

I am trying to read a simple json file that will possess the path to some audio files. Nothing complicated. Follow below the json:

{
  "audioSetup": {
    "buttonNumpad1AudioFile": "C:\\Users\\mypc\\Downloads\\Musica 1.mp3",
    "buttonNumpad2AudioFile": "C:\\Users\\mypc\\Downloads\\Musica 2.mp3",
    "buttonNumpad3AudioFile": "C:\\Users\\mypc\\Downloads\\Musica 3.mp3",
  }
}

I am using the following code to read the json file:

public static class Json
    {
        public static AudioSetup LoadAudioSetup()
        {
            using (StreamReader streamReader = File.OpenText(@"..\..\audioSetup.json"))
            {
                string json = streamReader.ReadToEnd();
                AudioSetup audioSetup = JsonConvert.DeserializeObject<AudioSetup>(json);
                return audioSetup;
            }
        }
    }

Also I created a class to use Deserializeobject:

public class AudioSetup    {
        public string buttonNumpad1AudioFile { get; set; }
        public string buttonNumpad2AudioFile { get; set; }
        public string buttonNumpad3AudioFile { get; set; }
    }

The data read by Streamreader is all right. The problem lies within the instance it creates after Jsonconvert.Deserializeobject(json) comes with the value properties null. I’ve tried many ways to do this and they all result in the properties with value null.

I simply cannot read the values inside audioSetup.buttonbuttonNumpad1AudioFile or the other two properties because they are always null after the deserialization process.

Can you give me a hand with that?

1 answer

0


Your JSON is an object that has a member that is an object with another 3 members, so you have two options, change your JSON to

{
    "buttonNumpad1AudioFile": "C:\\Users\\mypc\\Downloads\\Musica 1.mp3",
    "buttonNumpad2AudioFile": "C:\\Users\\mypc\\Downloads\\Musica 2.mp3",
    "buttonNumpad3AudioFile": "C:\\Users\\mypc\\Downloads\\Musica 3.mp3",
}

or create two classes where one has a property like the other, for example

public class AudioSetup    
{
        public string buttonNumpad1AudioFile { get; set; }
        public string buttonNumpad2AudioFile { get; set; }
        public string buttonNumpad3AudioFile { get; set; }
}

public class ContainerAudioSetup
{
         AudioSetup    audioSetup    {get; set;}
}
  • Thank you Vitor! Really the error was in the composition of my json file. Fixed problem!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.