简体   繁体   English

假物体好坏

[英]Dummy Objects Good or Bad

I am working on a project that communicates a lot of data with a server. 我正在与服务器通信大量数据的项目中。 This data is in a json format. 此数据为json格式。 We end up creating a lot of dummy objects to parse the json data. 我们最终创建了许多虚拟对象来解析json数据。 This leads to having a lot of classes that just contain class members. 这导致有很多只包含类成员的类。 Is there a better way of doing things? 有没有更好的做事方法?

thanks 谢谢

Assuming that you are using NewtonSoft's JSON parser or something similar, you have a couple of choices here. 假设您使用的是NewtonSoft的JSON解析器或类似工具,则这里有两个选择。 The usual use case here is to deserialize to a named type, thus: 这里通常的用例是反序列化为命名类型,因此:

var parsedMessage = JsonConvert.DeserializeObject<Message>(content.AsString());

If you have many types for each differnet JSON message type you wish to receive and wish to avoid to, you can do the following: 如果您希望接收并希望避免的每种differnet JSON消息类型有多种类型,则可以执行以下操作:

var parsedMessage = JsonConvert.DeserializeObject<dynamic>(content.AsString());

This will give you a dynamic object that you can inspect and should also work given other Json libraries. 这将为您提供一个动态对象,您可以对其进行检查,并且在其他Json库中也可以使用。 Alternatively, NetwtonSoft also provides the following method: 另外,NetwtonSoft还提供以下方法:

public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject);

This will allow you to deserialize to an anonymously typed object rather than a dynamic object. 这将允许您反序列化为匿名类型的对象,而不是动态对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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