NewtonJsonConvert的比较好搭配使用

(1)与关键字冲突,解决办法加@

var a = new
{
    @class=1,
};
var d = JsonConvert.SerializeObject(a);
Console.WriteLine(d);

output

{"class":1}

(2)接参数,dynamic神搭配!

var a = new
{
    @class=1,
    test=new List<int> { 3,4,5},
    ppp="this is a ppp"
};
var d = JsonConvert.SerializeObject(a);
Console.WriteLine(d);
dynamic b = JsonConvert.DeserializeObject(d);
Console.WriteLine(b.@class);
Console.WriteLine(b.test.Count);
Console.WriteLine(b.ppp);

该方法的应用场景还有EF Core中,查询数据,在不创建对应的类的情况下,直接获取数据。

(3)ExpandoObject:一个装数据和方法的动态袋子

dynamic a = new ExpandoObject();
            a.test = "jjjj";
            a.@class = "class";
            Console.WriteLine(a.test);
            Console.WriteLine(a.@class);


posted @ 2024-01-12 19:20  JohnYang819  阅读(25)  评论(0编辑  收藏  举报