I am trying to read a JSON file, rename the property names, and export a new JSON with the new names. As stated in this example, https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm, we can use JsonProperty to specify a different name internally in the code. However, when you export the json, it returns the original name. So in the example it still returned "release_date" instead of "ReleaseDate" when it was logged in the console. Is there any way to do this without creating a brand new object?
To clear things up, here is example of what I am trying to do:
JSON Input:
{ "name": "Starcraft", "release_date": "1998-01-01T00:00:00" } Object Used to deserialize the data:
public class Videogame { public string name{ get; set; } [JsonProperty("release_date")] public DateTime releaseDate { get; set; } } Code that is called:
var json = JsonConvert.DeserializeObject<Videogame>(File.ReadAllText(path)) Console.WriteLine(JsonConvert.SerializeObject(json)); Resulted Output:
{ "name": "Starcraft", "release_date": "1998-01-01T00:00:00" } Desired Output:
{ "name": "Starcraft", "releaseDate": "1998-01-01T00:00:00" } The only way that I currently know how to solve it is to create a new object and use it to serialize my output. Wasn't sure if there is any simpler way to do this.
JsonSerializerSettingsas shown in @VladStryapko's linked answer Use different name for serializing and deserializing with Json.Net. If the name mapping is not deterministic, consider usingConditionalNameContractResolverfrom JsonProperty WebApi request and response models.