JSON.NET自定义属性序列化



我在下面有一个类

public class Sample { 
    public string schema { get; set; } 
    public string version { get; set; } 
}

我正在寻找的输出是

{
    $schema : "some schema", 
    version : "1.1.1.1.1" 
}

我使用下面的代码来序列化

public class SchemaSerializer : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var schema = value as string;
        writer.WriteStartObject();
        writer.WritePropertyName("$schema");
        serializer.Serialize(writer, schema);
        writer.WriteEndObject();
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jsonObject = JObject.Load(reader);
        var properties = jsonObject.Properties().ToList();
        return new Schema
        {
            SchemaName = properties[0].Name.Replace("$", ""),
            Value = (string)properties[0].Value
        };
    }
    public override bool CanConvert(Type objectType)
    {
        return typeof(Schema).IsAssignableFrom(objectType);
    }
}

然而,这会产生低于的输出

{
   schema : {$schema : "some schema" } , 
   version : "1.1.1.1.1"
}

如何解决此问题?

JsonProperty与字符串属性名称解决了这个问题

  [JsonProperty(PropertyName = "$schema")]
public string Schema { get; set; }

相关内容

  • 没有找到相关文章

最新更新