gpt4 book ai didi

c# - System.Text.Json - 将嵌套对象反序列化为字符串

转载 作者:行者123 更新时间:2023-12-03 22:56:12 26 4
gpt4 key购买 nike

我正在尝试使用 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: Cannot get the value of a token type 'StartObject' as a string.



到目前为止我尝试了什么:
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: Cannot get the value of a token type 'StartObject' as a string.



什么是 cooking 我需要的东西的正确食谱?它使用 Newtonsoft.Json 以类似的方式工作。 .

更新

对我来说,保持嵌套的 JSON 对象尽可能原始是很重要的。所以,我会避免选择反序列化为 Dictionary并序列化回来,因为我害怕引入不需要的更改。

最佳答案

找到了如何正确读取 JsonConverter 中的嵌套 JSON 对象的正确方法.完整的解决方案如下:

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 在他的回答中所说,模型表示及其序列化没有混合。

关于c# - System.Text.Json - 将嵌套对象反序列化为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60401444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com