【发布时间】:2020-06-09 14:09:32
【问题描述】:
我正在尝试使用 System.Text.Json.JsonSerializer 部分反序列化模型,因此其中一个属性被读取为包含原始 JSON 的字符串。
public class SomeModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Info { get; set; }
}
示例代码
var json = @"{
""Id"": 1,
""Name"": ""Some Name"",
""Info"": {
""Additional"": ""Fields"",
""Are"": ""Inside""
}
}";
var model = JsonSerializer.Deserialize<SomeModel>(json);
应该生成模型,其中Info属性包含来自原始JSON的Info对象作为字符串:
{
"Additional": "Fields",
"Are": "Inside"
}
它不能开箱即用并引发异常:
System.Text.Json.JsonException: ---> System.InvalidOperationException: 无法将令牌类型“StartObject”的值作为字符串获取。
到目前为止我尝试了什么:
public class InfoToStringConverter : JsonConverter<string>
{
public override string Read(
ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
{
return reader.GetString();
}
public override void Write(
Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
并将其应用到模型中
[JsonConverter(typeof(InfoToStringConverter))]
public string Info { get; set; }
并将选项添加到JsonSerializer
var options = new JsonSerializerOptions();
options.Converters.Add(new InfoToStringConverter());
var model = JsonSerializer.Deserialize<SomeModel>(json, options);
仍然会引发相同的异常:
System.Text.Json.JsonException: ---> System.InvalidOperationException: 无法将令牌类型“StartObject”的值作为字符串获取。
什么是烹饪我需要的东西的正确食谱?它使用Newtonsoft.Json 以类似的方式工作。
更新
对我来说,保持嵌套的 JSON 对象尽可能原始很重要。所以,我会避免像反序列化为 Dictionary 并序列化回来这样的选项,因为我害怕引入不需要的更改。
【问题讨论】:
-
您还可以创建一个类并将
Info值存储在其实例中,就像在此thread 中所做的那样 -
要使用自定义转换器实现预期行为,您可以查看
JsonValueConverterKeyValuePair并了解如何正确读写复杂json结构的StartObject和EndObject
标签: c# json .net-core deserialization system.text.json