Search code examples
c#apiserializationjson.net

Is there a way to serialize Json Property name in Newtonsoft?


I have a class as shown below which I want to serialize such that the JSON key is the JsonPropertyName of the variable, but the serialized string has the variable name as the JSON key.

using System.Text.Json.Serialization
public class TestClass
{
   [JsonPropertyName("tst")]
   public string Test{ get; set; }
}

Serializer uses Newtonsoft.Json

var json = JsonConvert.SerializeObject(new TestClass {Test = "some value"})
Console.writeLine(json)
  • actual output: {"Test":"some value"}
  • expected output: {"tst":"some value"}

Is there a way to serialize the object with property name as the key {"tst":"some value"}


Solution

  • You have to use the JsonProperty() attribute and not the JsonPropertyName() attribute. You also have to include Newtonsoft.Json not System.Text.Json that is the JSON library used for .NET:

    using Newtonsoft.Json;
    public class TestClass
    {
        [JsonProperty(PropertyName ="tst")]
        public string Test{ get; set; }
    }