关于System.Text.Json使用的笔记

System.Text.Json库与Newtonsoft.Json同样用于处理json序列化,两者的比较见 https://schneids.net/comparing-newtonsoft-json-with-system-text-json/

 1 public class TestEntity
 2 {
 3     public string id { get; set; }
 4 
 5     public Dictionary<string, JsonElement> dict { get; set; }
 6 }
 7 
 8 void main(){
 9     string jstring = "{ \"id\":\"id\", \"dict\": { \"a\":0.1, \"b\":\"b\", \"c\":1 } }";
10 
11     var t = JsonSerializer.Deserialize(jstring, typeof(TestEntity)) as TestEntity;
12 
13     double v = t.dict["a"].GetDouble();
14 }

如上示例中使用 System.Text.Json 名空间,有如下注意点:

  1. 反串行化支持字典类型的生成,包括自动实例化字典实例;
  2. 若字典构建中出现类型的混合,例如既有字符串又有数值,则构建Dictionary<String,String>类型字典会失败;
  3. 若尝试使用Dictionary<String,Object>类型,则其Object对象中实际存放的是JsonElement实例,而非CLR基础类型;
  4. 通过JsonElement的Get方法组,可以将所需的值转换出来。
posted @ 2021-11-18 16:16  崩溃侠  阅读(545)  评论(0编辑  收藏  举报
友情链接: Heroius' Ideas 沈阳因斯福环保安全科技有限公司 东北大学工业爆炸防护研究所