1

I have a class looks like below

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

Output I am looking for is

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

I used below code to serialize the

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);
    }
}

However this produces output below

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

How to fix this?

1 Answer 1

1

JsonProperty with string property name solve this problem

  [JsonProperty(PropertyName = "$schema")]
public string Schema { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.