Prasoon
Prasoon

Reputation: 217

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)

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

Upvotes: 7

Views: 19775

Answers (1)

Ubaldo Vitiello
Ubaldo Vitiello

Reputation: 221

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

Upvotes: 18

Related Questions