作者erspicu (.)
看板C_Sharp
标题[心得] .NET 6.0的System.Text.Json的改善
时间Wed Dec 1 09:41:06 2021
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));
}
现在多数的常见需要用到的功能 内建的都足以胜任了
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 125.228.12.47 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1638322871.A.DF6.html
1F:推 neo5277: 有JObject我就可以放心啦 12/03 11:38
2F:推 forewero: 但我每次开专案都是先把json替换成原本的 哈哈哈哈 12/30 18:57
3F:推 j835111: 之前好像就有JsonElement了吧? 01/04 00:08