This repository was archived by the owner on Sep 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
Json
Noel Berry edited this page Mar 31, 2020
·
4 revisions
This library provides a simple Json reader and writer. I wasn't really happy with a lot of the existing solutions and wanted something very simple and small, that could optionally read and write non-strict Json in the form of Hjson.
You can quickly parse Json by using the JsonValue.FromFile method:
var json = JsonValue.FromFile("data.json");Alternatively, you can create a Json reader and parse it that way:
using var stream = File.OpenRead("data.json");
var reader = new JsonTextReader(stream);
var json = reader.ReadObject();You can then use the JsonValue to retrieve data
// Get a string value:
var name = json["name"].String;
// Get a number value:
var number = json["age"].Int;
// Iterate over an array
foreach (var value in json["list"].Values)
Console.WriteLine(value.String);
// Iterate over an object
foreach (var (key, value) in json["objects"].Pairs)
Console.WriteLine($"{key}: {value}");There are two ways to write Json:
var json = new JsonObject();
json["name"] = "Nobody";
json["age"] = 25;
var friends = new JsonArray();
friends.Add("Nobody");
friends.Add("Another Person");
json["friends"] = friends;
json.ToFile("output.json");var writer = new JsonTextWriter("output.json");
writer.ObjectBegin();
writer.Key("name");
writer.Value("Nobody");
writer.Key("age");
writer.Value(25);
writer.Key("friends");
writer.ArrayBegin();
writer.Value("Somebody");
writer.Value("Another Person");
writer.ArrayEnd();
writer.ObjectEnd();Guides
API
Examples