C#でJSONを読み込む - 2024/6/15
C#でJSONを読み込む場合、Newtonsoft.Json というサードパーティのライブラリがよく利用されていたらしい。
個人的にはJSONの読み込みがサードパーティなのはどうなの?的なことを思っていたので、.configファイルを使ったりしてた。個人的に開発してるだけやし・・・
ただ今回調べたところ、System.Text.Jsonなるライブラリが公式で用意されてるらしかったので、使い方をメモ。
使い方例
code:test.cs
using System.Text.Json;
public class User {
public string name { get; set; } = "Oliver";
public int age { get; set; } = 20;
}
public static User jsonParse(string json) {
try {
User? user = JsonSerializer.Deserialize<User>(json);
if (config == null) return new User();
return user;
} catch (JsonException e) {
Console.WriteLine(e.Message);
return new User();
}
}
code:example.json
{
"name": "Jake",
"age": 30
}
大雑把な使い方としては、保持したい情報の入れ物となるクラスを作っておき、これをJsonSerializer.Deserializeに型として渡し、一緒に JSON 形式の文字列を渡すと、良い感じに値を保持したインスタンスを返してくれる。
JSONの中にあるキーと、クラスの持つメンバの名前が一致していれば良さそう。
注意点として、クラスのメンバにはget・setのプロパティを書くこと。
当たり前かもしれないが、setを使って値を入れているっぽいので。
これを無視してsetを書かないで動かして、「全然入らんが?」みたいなので時間を喰った(´・ω・`)
参考
https://learn.microsoft.com/ja-jp/dotnet/standard/serialization/system-text-json/migrate-from-newtonsoft?pivots=dotnet-9-0
https://learn.microsoft.com/ja-jp/dotnet/standard/serialization/system-text-json/deserialization
https://www.terry-u16.net/entry/system-text-json
https://qiita.com/cp3/items/1eb0293aa06655a403d4
https://iwasiman.hatenablog.com/entry/20210614-CSharp-json
#csharp
#dotnet