JSON.NET 属性的自定义序列化

JSON.NET custom serialization of properties

我有一个 class 看起来像下面

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 with string 属性 name 解决这个问题

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