Home > Software engineering >  Deserialize JSON into C# Queue of Custom Object
Deserialize JSON into C# Queue of Custom Object

Time:11-25

I feel like a dingdong not being able to figure this out, but hoping someone can either help me or point me in the right direction.

I'm currently converting individual files for a game i'm working on into a JSON Object. Currently, the structure of the song is as follows:

        public readonly int Id = 1;

        public readonly int BPM = 120;
        public readonly string Name = "Baby's";

        public readonly string Artist = "Brian";

        protected Song SongFile;

        public Queue<NoteChart> Chart = new Queue<NoteChart>();

        Chart.Enqueue(new NoteChart { gemType = 1, Key = "D", Lane = 8, beatTime = new TimeSpan(0, 0, 0, 5, 84) });
 

Pretty standard stuff I presume. Anyways, i'm having a iddue turning that Chart.Enqueue into a JSON object so I can parse it that way instead of having it typed out. So far I have:

  "Id": 1,
  "BPM": 120,
  "Name": "Baby",
  "Artist": "Brian",
  "SongFile": "Songs/Baby",
  "Chart": {
  }

But as you can see, i'm stuck on the Chart portion. How would I succesfully map it into JSON to be converted into C#? Or is there a better way of doing this?

Thank you!

CodePudding user response:

I can not find any problem

var chartItem = new ChartItem();

var json = JsonConvert.SerializeObject(chartItem, Newtonsoft.Json.Formatting.Indented);

public class ChartItem
{
    public readonly int Id = 1;

    public readonly int BPM = 120;
    public readonly string Name = "Baby's";

    public readonly string Artist = "Brian";

    protected string SongFile;

    public Queue<object> Chart =new ();
    
    public ChartItem ()
    {
        Chart.Enqueue(new  { gemType = 1, Key = "D", Lane = 8, beatTime = new TimeSpan(0, 0, 0, 5, 84) });
    }
    
}

json

{
  "Id": 1,
  "BPM": 120,
  "Name": "Baby's",
  "Artist": "Brian",
  "Chart": [
    {
      "gemType": 1,
      "Key": "D",
      "Lane": 8,
      "beatTime": "00:00:05.0840000"
    }
  ]
}
  • Related