通过转换器与反序列化转换 Json 字符串

Conversion of Json String by converter vs deserialization

我有一个客户端服务器应用程序,客户端以 json 字符串格式发送数据,当我收到消息时,我希望将此消息转换为具体类型[在不同程序集中定义],这里我有两个选项:

  1. 使用类型转换器将字符串转换为具体类型。
  2. 使用反序列化器转换为具体 class。 我试图了解哪个选项更好,但无法进行任何具体比较。 谁能解释一下两者的优点和局限性?

让转换器将 JSON 转换为那种类型的想法真的很糟糕。 您最好使用 JSON 反序列化器,例如最近得到显着改进的 Newtonsoft.JSON 或 System.Text.Json。我更喜欢使用 Newtonsoft.JSON,因为它对输入数据不太敏感,因此,要将字符串转换为您需要的类型,您只需编写类似 tihs:

的内容
//Let's assume your type is Foo, and a string to deserialize is named json
Foo foo = JsonConvert.DeserializeObject<Foo>(json);

就是这样!现在,您的 foo 变量包含所有 Foo class 数据,这些数据存储在 json.

使用解串器是最好的选择,除非您需要一个非常快的自定义转换器,前提是您确定它真的会更快。

P.S。如果您使用 ASP.NET 作为服务器应用程序,您甚至不需要做这样的事情。只需将 [FromBody] 放在您的控制器函数中,即可转换存储在请求正文中的数据,例如:

[HttpGet]
public void IActionResult GetFoo([FromBody] Foo foo)
{
//your code here
}

希望对您有所帮助! ;)

如果您默认使用 Json,请使用反序列化。

实际使用TypeConverter

  1. 类型之间的转换,不一定是字符串和对象之间的转换。支持任何类型的对象转换。
  2. 在 UI 中用于在字符串表示之间动态收费,主要不是 JSON
  3. 甚至在序列化库中用于处理自定义类型:https://www.newtonsoft.com/json/help/html/SerializationGuide.htm

When serializing a dictionary, the keys of the dictionary are converted to strings and used as the JSON object property names. The string written for a key can be customized by either overriding ToString() for the key type or by implementing a TypeConverter.

另一方面序列化:

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

这不是关于类型之间的转换:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/

既然你说的是传输,那么序列化就是要走的路。