Can you Instantiate an Object Instance from JSON in .NET?

前端 未结 5 1648
一向
一向 2021-01-02 09:20

Since Object Initializers are very similar to JSON, and now there are Anonymous Types in .NET. It would be cool to be able to take a string, such as JSON, and create an Anon

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-02 09:47

    There are languages for .NET that have duck-typing but it's not possible with C# using Dot.Notation since C# requires that all member references are resolved at compile time. If you want to use the Dot.Notation, you still have to define a class somewhere with the required properties, and use whatever method you want to instantiate the class from the JSON data. Pre-defining a class does have benefits like strong typing, IDE support including intellisense, and not worrying about spelling mistakes. You can still use anonymous types:

     T deserialize(string jsonStr, T obj) { /* ... */}
    
     var jsonString = "{FirstName='Chris', LastName='Johnson, Other='unused'}";
     var person     = deserialize(jsonString, new {FirstName="",LastName=""});
     var x          = person.FirstName; //strongly-typed
    

提交回复
热议问题