1

I have a json from a video game with around 1000 values at the root level and uses snake case keys, how can I deserialize it into multiple classes with System.Json.Text ? Thanks

For example

{
    "onlinepvp_kills:all": 0,
    "onlinepve_kills:all": 0
}

to

public class Online
{
    public PVP PVP { get; set; }
    public PVE PVE { get; set; }
}

public class PVP
{
    public int Kills { get; set; }
}

public class PVE
{
    public int Kills { get; set; }
}
Random
  • 13
  • 2

1 Answers1

1

Your JSON schema doesn't directly match your class. You might be better off creating classes designed to make deserialization easier, then use the the Adapter Pattern create classes that fit your needs that consume the c# json versions.

public class OnlineKillsSource
{
  
  [JsonPropertyName("onlinepvp_kills:all")]
  public int PVP { get; set; }
  [JsonPropertyName("onlinepve_kills:all")]
  public int PVE { get; set; }
}

Then use the Adapter Pattern, with a constructor:

public class Online
{
    public (OnlineKillsSource source)
    {
      PVP = new PVP { Kills = source.PVP };
      PVE = new PVE { Kills = source.PVE };
    }

    public PVP PVP { get; set; }
    public PVE PVE { get; set; }
}

public class PVP
{
    public int Kills { get; set; }
}

public class PVE
{
    public int Kills { get; set; }
}

Usage:

JsonSerializer.Deserialize<OnlineKillsSource>(jsonString);

var online = new Online(OnlineKillSource);

Now the advantage to this that you Separate the Concerns of deserializing external data and the transformation of the data into a standard consumable.

If the source of your Data changes the JSON schema, you have much less code to change to keep your code working.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150