[心得] .NET 6.0的System.Text.Json的改善

楼主: erspicu (.)   2021-12-01 09:41:06
6.0 后多了 System.Text.Json.Nodes
基本上离完善接近 Newtonsoft.Json 的功能又跨一大步
之前大概能胜任序列化.反序列化.PARSE和READ
在6.0后多了 JsonObject , JsonArray
不需要简单为了串一个JSON特别再定义一个CLASS去做反序列
Newtonsoft版本
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
private void button1_Click(object sender, EventArgs e)
{
List<string> list_org = new List<string>() { "aa", "bb", "cc" };
string list2jsonStr = JsonConvert.SerializeObject(list_org);
Console.WriteLine(list2jsonStr);
List<string> listfromjsonStr = new List<string>();
listfromjsonStr =
JsonConvert.DeserializeObject<List<string>>(list2jsonStr);
Console.WriteLine(listfromjsonStr[0]);
JObject jobj = new JObject();
JObject jobj2 = new JObject();
jobj2["aa"] = "11";
jobj2["Bu"] = "22";
jobj["aaa"] = "cc";
jobj["yy"] = jobj2;
Console.WriteLine(JsonConvert.SerializeObject(jobj));
}
System.Text.Json版本
https://tinyurl.com/34utw32c
https://tinyurl.com/4h3cnt4x
using System.Text.Json;
using System.Text.Json.Nodes;
private void button1_Click(object sender, EventArgs e)
{
List<string> list_org = new List<string>() { "aa", "bb", "cc" };
string list2jsonStr = JsonSerializer.Serialize(list_org);
Console.WriteLine(list2jsonStr);
List<string> listfromjsonStr = new List<string>();
listfromjsonStr =
JsonSerializer.Deserialize<List<string>>(list2jsonStr);
Console.WriteLine(listfromjsonStr[0]);
//.NET 6 后 从 System.Text.Json.Nodes 新增 JsonObject , JsonArray
JsonObject jobj = new JsonObject();
JsonObject jobj2 = new JsonObject();
jobj2["aa"] = "11";
jobj2["Bu"] = "22";
jobj["aaa"] = "cc";
jobj["yy"] = jobj2;
Console.WriteLine(JsonSerializer.Serialize(jobj));
}
现在多数的常见需要用到的功能 内建的都足以胜任了
作者: neo5277 (I am an agent of chaos)   2021-12-03 11:38:00
有JObject我就可以放心啦
作者: forewero (木日一)   2021-12-30 18:57:00
但我每次开专案都是先把json替换成原本的 哈哈哈哈
作者: j835111   2020-01-04 00:08:00
之前好像就有JsonElement了吧?

Links booklink

Contact Us: admin [ a t ] ucptt.com