【发布时间】:2019-02-22 14:30:30
【问题描述】:
我正在从服务器反序列化一些 JSON,这在很大程度上很简单:
{
"id": "ABC123"
"number" 1234,
"configured_perspective": "ComplexPerspective[WithOptions,Encoded]"
}
然而,“configured_perspective”属性是一个不幸的情况,服务器使用一个奇怪的组合字符串,而嵌套对象会更好。
为了减轻 .NET 用户的痛苦,我将其转换为对象模型中的自定义类:
public class Example
{
public string id { get; set; }
public int number { get; set; }
public Perspective configured_perspective { get; set; }
}
// Note, instances of this class are immutable
public class Perspective
{
public CoreEnum base_perspective { get; }
public IEnumerable<OptionEnum> options { get; }
public Perspective(CoreEnum baseArg, IEnumerable<OptionEnum> options) { ... }
public Perspective(string stringRepresentation) {
//Parses that gross string to this nice class
}
public static implicit operator Perspective(string fromString) =>
new Perspective(fromString);
public override string ToString() =>
base_perspective + '[' + String.Join(",", options) + ']';
}
如您所见,我已经组合了一个自定义类 Perspective,它可以在 JSON 字符串之间进行转换,但我似乎无法让 Newtonsoft JSON 自动将字符串转换为我的 Perspective 类。
我尝试让它使用[JsonConstructor] 属性调用字符串构造函数,但它只是使用null 调用构造函数,而不是使用JSON 中存在的字符串值。
我的印象(基于https://stackoverflow.com/a/34186322/529618)JSON.NET 将使用隐式/显式字符串转换运算符将 JSON 中的简单字符串转换为目标类型的实例(如果可用),但它似乎忽略了它,并且只返回错误:
Newtonsoft.Json.JsonSerializationException:找不到用于透视类型的构造函数。一个类应该有一个默认构造函数、一个带参数的构造函数或一个标有 JsonConstructor 属性的构造函数。路径'configured_perspective'
我试图避免为我的Example 类编写自定义 JsonConverter - 我很确定会有一种开箱即用的方法将简单的字符串值转换为非字符串属性类型,只是还没找到。
【问题讨论】:
标签: c# json json.net deserialization implicit-conversion