Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple parser from JSON string to Dictionary

I want to avoid importing a huge library to gain full JSON support.

My use case is REALLY simple: I need a parser to handle one specific case of JSON, where both key and value are strings, ie. { "name": "David" }. No nesting, no arrays, no object serialization.

The reason being, I use JSON only for i18n, and I have structure my translation files to be flat JSON.

  • Is it a good idea to hand roll my own parser?
  • Is there one out there already?
  • Are there easier solutions to my problem?

EDIT: yes, I do know JSON.net is the defacto solution for .NET, but it's not the solution for Unity (not natively). I really only need a tiny portion of its power.

like image 715
bitinn Avatar asked Feb 21 '26 00:02

bitinn


2 Answers

System.Json might do the trick for you.

The JsonValue.Parse() Method parses JSON text and returns a JsonValue like

JsonValue value = JsonValue.Parse(@"{ ""name"": ""David"" }");

You can also have a look at The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server.

var Names = new JavaScriptSerializer().Deserialize<YourNameClass>(json);
like image 97
Mohit S Avatar answered Feb 23 '26 13:02

Mohit S


OK I found one! https://github.com/zanders3/json

Has decent tests, minimal features and likely designed for my specific use case.

To load a JSON file:

Dictionary<string, object> locales = new Dictionary<string, object>();

TextAsset file = Resources.Load(name) as TextAsset;
var locale = file.text.FromJson<object>();
locales.Add(name, locale);

To use the JSON dictionary:

string activeLocale = "en-US";
var locale = locales[activeLocale] as Dictionary<string, object>;
var translation = locale[key] as string;

Dead simple.

like image 20
bitinn Avatar answered Feb 23 '26 14:02

bitinn