글쎄요 런타임의 자원이나 최신닷넷에 대한 의존성에 극단적인 제약이 있다면 필요할까 싶지만 예시코드의 스타일만 봤을때는 Newtonsoft.Json.Linq 혹은 System.Text.Json.Nodes 를 사용하는것과의 차이를 잘 모르겠습니다.
강타입의 수혜를 최대한으로 누리고자 Serialization을 권장하는거지 방법이 한정되있지는 않아용
json생성
using System.Text.Json.Nodes;
var color = System.Drawing.Color.White;
var doc = new JsonObject
{
["ok"] = true,
["hex"] = "#FFFFFF",
["name"] = null,
["rgb"] = new JsonObject
{
["r"] = color.R,
["g"] = color.G,
["b"] = color.B
}
};
Console.WriteLine(doc);
using System.Text.Json.Nodes;
bool TryParse(string body, out string? imageJson, out (int x, int y)? point)
{
try
{
var id = JsonNode.Parse(body);
imageJson = (string)id["image"];
var p = id["point"];
point = ((int)p["x"], (int)p["y"]);
return true;
}
catch
{
imageJson = null;
point = null;
return false;
}
}
Console.WriteLine(new {
good = TryParse("""{"image":"😺","point":{"x":1,"y":2}}""", out var img, out var p),
img, p
});