gpt4 book ai didi

c# - 对于错误的类型,反序列化的 JSON 对象不为空

转载 作者:行者123 更新时间:2023-12-05 02:26:53 24 4
gpt4 key购买 nike

如果我有以下c#记录:

public record MyRecord(string EndPoint, string Id);

我有一些 json,我试图将其反序列化为我的类型:

var myType= JsonSerializer.Deserialize<MyRecord>(
jsonStr,
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}
);

if(myType is null)
{
...
}

其中 jsonStr 不是 MyRecord 类型,而是其他类型,结果 myType 而不是 null,只是 MyRecord 的一个实例但具有空属性。如果返回的类型不为空,我如何检查它是否无效?

最佳答案

JsonSerializer 不会假设 json 字符串内容的缺失,前提是它至少与目标结构的格式相同(例如 "{ }").

因此,您需要检查其中一个属性的有效性以及对象本身:

var jsonStr = "{}";

var myType = JsonSerializer.Deserialize<MyRecord>(
jsonStr,
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}
);

if (!string.IsNullOrEmpty(myType?.Id))
{
var x = myType;
}

请注意,类的行为也是相同的:

public class MyClass
{
public string EndPoint { get; set; }
public string Id { get; set; }
}

var myType2 = JsonSerializer.Deserialize<MyClass>(
jsonStr,
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}
);

if (!string.IsNullOrEmpty(myType2?.Id))
{
var x = myType;
}

如评论中所述,您可以选择创建一个覆盖序列化行为的自定义转换器。

public class MyRecordConverter : JsonConverter<MyRecord>
{
public override MyRecord Read(ref Utf8JsonReader reader, Type typeToConvert,
JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
return null;
}

var endpoint = string.Empty;
var id = string.Empty;

while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
break;
}

var propertyName = reader.GetString();
reader.Read();

if (propertyName.Equals(nameof(MyRecord.EndPoint),
StringComparison.OrdinalIgnoreCase))
{
endpoint = reader.GetString();
}
else if (propertyName.Equals(nameof(MyRecord.Id),
StringComparison.OrdinalIgnoreCase))
{
id = reader.GetString();
}
}

if (string.IsNullOrEmpty(endpoint) && string.IsNullOrEmpty(id))
{
return null;
}

return new MyRecord(endpoint, id);
}

public override void Write(Utf8JsonWriter writer, MyRecord value,
JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}

当传递给反序列化调用时:

var myType3 = JsonSerializer.Deserialize<MyRecord>(
jsonStr,
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
Converters =
{
new MyRecordConverter()
}
}
);

上面的空 json 对象将返回 null 而不是初始化的记录。

关于c# - 对于错误的类型,反序列化的 JSON 对象不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73571714/

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