Can I deserialize json to anonymous type in c#?

前端 未结 7 694
半阙折子戏
半阙折子戏 2021-02-04 07:13

I read from the DB a long json. I want just one attribute of that json.

I have got two options: a. Create an interface for that json and deserialize to that interface.

7条回答
  •  深忆病人
    2021-02-04 07:28

    Regex must be absolutely out of any discussion. Just forget about it, it's as if it never existed.

    Creating and working with strong types is a good thing and probably the way I would go.

    But if you want, you could also use dynamic:

    class Program
    {
        static void Main()
        {
            var json = "{ 'foo': { 'bar': 'bar value', 'baz': [ 1, 2, 3 ] } }";
            var serializer = new JavaScriptSerializer();
            dynamic value = serializer.DeserializeObject(json);
            Console.WriteLine(value["foo"]["baz"][1]);
        }
    }
    

    prints 2 on the console.

提交回复
热议问题