Thursday, December 3, 2015

Stop The Madness: Using json in csharp

I want to read some json in csharp. It shouldn't bee too hard, there are some great libraries out there - Json.NET comes to mind. The problem with most of the existing libraries is that they do too much - I don't really need xml support, or linq or json path. In fact, all I want is the JSON.parse and JSON.stringify that I love so much in javascript. And so here it is - JSON2.cs.

The first thing you're going to say is 'Why are you boxing values? Where is dynamic?'. Actually, the 1st version used dynamic, and it's very cool to use, because you can access json values as dot properties. But dynamic is not allowed in the Unity version of csharp. Too bad, but I can see that dynamic could become a performance issue. So we will use bracketed notation. There are 2 helper classes - JSONObject and JSONArray. And 2 helper functions that really just wrap a cast - JSON.Object and JSON.Array.

The reason for all of this madness? So I can store a small database in my game with preferences and local leaderboard values:

 * Get Leaderboard
 * @param {int} count
 * @returns {JSONArray} the top count scores.
 public static JSONArray GetLeaderboard(int count) {
  var jsonQueryAll = string.Format(@"{{""limit"":{0}, ""sort"": [[""score"", ""DESC""]]}}", count);
  return db.QueryAll("leaderboard", jsonQueryAll);

To facilitate this, I've also ported localStorageDB.js to PlayerPrefDB.cs. You can see it in action, I'm using it in my first Unity game, Shmup Warz. Yes, I'm porting Shmup Warz also from typescript to csharp. Where does the madness stop?!

No comments:

Post a Comment