是否可以将任何空的 Json 对象转换为 null?

问题描述 投票:0回答:1

我正在使用可以返回空 Json 作为可能值的 API。

空的Json"{}"也可以出现在嵌套字段中,比如

foo
有一个对象类型的字段名
field3
,如果该对象类型的字段都是空值,它也可以是{} .

我的问题是,如何将任何“{}”json 值转换为 null,以便我可以将我的类建模为可为空?

API 响应示例:

{
 "foo" : {}
}

{
 "foo" : {
  "field1" : 123,
  "field2" : "somestring"
  "field3" : {}
 }
}

我想反序列化成的示例类

public class Foo 
{
  public int? Field1 { get; set; }
  public string? Field2 { get; set; }
  public Bar? Field3 { get; set; }
}
c# json.net
1个回答
0
投票

您可以使用记录和自定义反序列化器

using System.Text.Json;
using System.Text.Json.Serialization;

var json = "{\"foo1\" : {}, \"foo2\" : {}}";
var foo = JsonSerializer.Deserialize<FooContainer>(json);
Console.WriteLine(foo);

record Foo(int? i){
    public static readonly Foo ALL_NULL_FOO = new Foo(i: null);
};
record FooContainer
{
    [JsonConverter(typeof(NullableFooConverter))]
    public Foo? foo1 {get;set;}
    // no attribute on this guy
    public Foo? foo2 {get;set;}
}

class NullableFooConverter : JsonConverter<Foo>
{
    public override Foo? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var desFoo = JsonSerializer.Deserialize<Foo>(ref reader, options);
        return (desFoo == Foo.ALL_NULL_FOO) ? null : desFoo;
    }

    public override void Write(Utf8JsonWriter writer, Foo value, JsonSerializerOptions options)
        => writer.WriteStringValue(JsonSerializer.Serialize(value, options: options));
    
}

这是输出:

FooContainer { foo1 = , foo2 = Foo { i =  } }

意味着 foo1 为 null,而 foo2 是属性 i 设置为 null 的 foo

记录适用于此,因为它们表示一个实体并且不是通过引用相等,就像类一样,但如果所有属性都相等。

© www.soinside.com 2019 - 2024. All rights reserved.