我试图使用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
序列化和序列化那样的选项,因为我担心会引入不需要的更改。
找到了正确的方法,如何正确读取中的嵌套JSON对象JsonConverter
。完整的解决方案如下:
public class SomeModel
{
public int Id { get; set; }
public string Name { get; set; }
[JsonConverter(typeof(InfoToStringConverter))]
public string Info { get; set; }
}
public class InfoToStringConverter : JsonConverter<string>
{
public override string Read(
ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using (var jsonDoc = JsonDocument.ParseValue(ref reader))
{
return jsonDoc.RootElement.GetRawText();
}
}
public override void Write(
Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
在代码本身中,甚至不需要创建选项:
var json = @"{
""Id"": 1,
""Name"": ""Some Name"",
""Info"": {
""Additional"": ""Fields"",
""Are"": ""Inside""
}
}";
var model = JsonSerializer.Deserialize<SomeModel>(json);
Info
属性中的原始JSON文本甚至包含示例中引入的额外空格,以提高可读性。
@PavelAnikhouski在他的回答中没有提及模型表示及其序列化。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句