简体   繁体   中英

How to create C# class code from dynamic object?

Someone send JSON to me. It has same format each time. It can be deserialised into dynamic object with var dyn = JsonConvert.DeserializeObject<dynamic>(rawJson); . Documentation is bad for my current version or JSON provider while I want to have code-hilighting on all the fields I get.

How to get C# class code from dynamic object so that I could then deserialise into that generated type instead of dynamic object with var oldschool = JsonConvert.DeserializeObject<GeneratedTypeFromDynamicObject>(rawJson); ?

Generating a type at run-time isn't going to help you much because you need the type at compile time in order to get early binding, type safety, and Intellisense. A much more practical idea would be to do the following:

  1. Get a representative sample of a JSON string from your logs.

  2. Paste the JSON into a class and save it as c# code in your project.

  3. Start using the class as the type argument to your deserialization call.

在此处输入图片说明

After you do this, you will have the correct class in your code base and you can compile against it. If the folks that send you the JSON decide to change the message, any new fields will be ignored. If they start removing things though then you have problems, just as if they had changed the WSDL for a SOAP service. You will have to repeat the above steps, and correct any breaking changes in your code. The nice thing is that you will have the breaking changes to guide you at compile time :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM