c# - 如何重命名和重新映射具有非法 json 字段名称的字段

标签 c# json deserialization restsharp json2csharp

我已经使用 json2csharp 生成了一些很好的 c# 类,我可以将 json 反序列化到其中。

除了 json2csharp 将一些字段命名为 invalid_name 之外,它实际上按预期工作。我将它们重命名为有效的 csharp 名称,但在序列化时这些类为空。

我找到了 this other SO post ...其中一位回答者说了以下...

Keep in mind the class I have pasted below will not work directly, because of the naming of some of the fields in the json. You may have to rename them manually and map them.

这正好描述了我的问题。不幸的是,答案没有提供任何关于如何“映射它们”的线索。那么有人可以告诉我如何手动将一些 json 数组映射到 c# 类。

顺便说一句,我正在使用 RestSharp 反序列化器。

有什么想法吗?

最佳答案

如果您使用 JSON.NET 作为基础或 JSON 解析,您可以重命名您的属性,然后用属性修饰它们以将它们重新对齐到原始 JSON 对象。

一个示例是 JSON 中名为 1 的属性,它在 C# 中无效。这可以使用以下方法纠正:

 [JsonProperty("1")]
 public int? One { get; set; }

如果您想在类级别编辑,还有一个 JsonObject 属性,还有一个 JsonIgnore 对象来忽略属性的序列化。

关于c# - 如何重命名和重新映射具有非法 json 字段名称的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14917430/

相关文章:

c# - .NET 中的通用线程池

c# - 使用新的 .net-core-3 json 序列化程序进行依赖注入(inject)

java - Spring MVC 4.1.x RestFul 服务抛出 Json Not Acceptable

c# - 在应用程序之间共享序列化对象

iOS 序列化/反序列化无法正常工作

c# - 如何确定作为参数传递的 object[] 包含什么?

c# - 从 appsettings c# 读取 json 数组

PHP/json_encode : dealing with mixed arrays and objects with numeric properties

python - 如何使用 PyMongo find() 搜索嵌套数组属性?

java - jsonrpc4j : How to add type info to parameters?