Skip to content

Instantly share code, notes, and snippets.

@svick
Last active November 10, 2022 10:02
Show Gist options
  • Save svick/2a321625f068af5b6396b38e1b05cceb to your computer and use it in GitHub Desktop.
Save svick/2a321625f068af5b6396b38e1b05cceb to your computer and use it in GitHub Desktop.
using System.Text.Json;
using System.Text.Json.Serialization;
string json = """
{
"ISBN:9780544003415": {
"bib_key": "ISBN:9780544003415",
"info_url": "https://openlibrary.org/books/OL26885115M/The_lord_of_the_rings"
}
}
""";
var options = new JsonSerializerOptions
{
Converters = { new IsbnConverter() }
};
var result = JsonSerializer.Deserialize<Dictionary<Isbn, YourItemModel>>(json, options);
Console.WriteLine(result[new("ISBN:9780544003415")].info_url);
record YourItemModel(string bib_key, string info_url);
record struct Isbn
{
public string Number { get; }
public Isbn(string isbnString)
{
var parts = isbnString.Split(':');
if (parts is [ "ISBN", var number ] && number.Length is 10 or 13)
Number = number;
else
throw new Exception("Incorrect ISBN.");
}
public override string ToString() => $"ISBN:{Number}";
}
class IsbnConverter : JsonConverter<Isbn>
{
public override Isbn ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> new(reader.GetString());
public override Isbn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> throw new NotImplementedException();
public override void Write(Utf8JsonWriter writer, Isbn value, JsonSerializerOptions options)
=> throw new NotImplementedException();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment