Can I deserialize json to anonymous type in c#?

前端 未结 7 696
半阙折子戏
半阙折子戏 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:29

    Old thread, but here goes another method on .NET 3.5: you can cast the object returned by DeserializeObject to a Dictionary. It's kind of the same solution as using the .NET 4.0 dynamic keyword:

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    Object obj = serializer.DeserializeObject("{ 'name': 'vinicius fonseca', 'age': 31 }");
    Dictionary ret = (Dictionary)obj;
    Console.WriteLine(ret["name"].GetType().Name); // Output: String
    Console.WriteLine(ret["name"].ToString()); // Output: vinicius fonseca
    Console.WriteLine(ret["age"].GetType().Name); // Output: Int32
    Console.WriteLine(ret["age"].ToString()); // Output: 31
    

    Hope it helps someone.

    Regards

提交回复
热议问题