Reputation: 217
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)
{"Test":"some value"}
{"tst":"some value"}
Is there a way to serialize the object with property name as the key
{"tst":"some value"}
Upvotes: 7
Views: 19775
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