gpt4 book ai didi

c# - JsonConverter 不会用破折号(连字符)转换枚举

转载 作者:行者123 更新时间:2023-12-04 14:08:57 25 4
gpt4 key购买 nike

<分区>

我正在尝试使用 .NET Core (5) System.Text.Json JsonSerializer.Deserialize() 将 JSON 对象转换为 C# 类,但它抛出了 JsonException。我相信原因是因为它试图转换为枚举的字符串值包含破折号(连字符)。枚举看起来像这样:

    [JsonConverter(typeof(JsonStringEnumConverter))]
public enum TypeEnum
{
[EnumMember(Value = "loopback")]
Loopback = 1,

[EnumMember(Value = "link-local")]
LinkLocal = 2,
}

JSON 对象相当大,但导致异常的部分是这样的:

{
"address": "fe80::3617:ebff:fec0:b54c/64"
"family": "inet6",
"type": "link-local"
}

当 JsonSerializer 遇到 "type":"link-local"时,它不喜欢 "link-local"并抛出。有什么办法可以解决这个问题吗?

谢谢。

被要求异常(exception),所以这里是:

 System.Text.Json.JsonException : The JSON value could not be converted to DmIfInfoAddr+TypeEnum. Path: $[0].addrs[0].type | LineNumber: 0 | BytePositionInLine: 144.
Stack Trace:
ThrowHelper.ThrowJsonException(String message)
EnumConverter`1.ReadWithQuotes(Utf8JsonReader& reader)
EnumConverter`1.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options)
JsonPropertyInfo`1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
IEnumerableDefaultConverter`2.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, TCollection& value)
JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
JsonPropertyInfo`1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
IEnumerableDefaultConverter`2.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, TCollection& value)
JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
JsonSerializer.ReadCore[TValue](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
JsonSerializer.ReadCore[TValue](Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options)
JsonSerializer.Deserialize[TValue](String json, Type returnType, JsonSerializerOptions options)
JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)

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