1

I have a source JSON object that I get from a server that looks like this:

{
"Property A": .098
}

I have a C# class that I deserialize the JSON into using the following:

public class foo {
    [JsonProperty("Property A")]
    public decimal PropertyA{ get; set;}
}

var ret = JsonConvert.DeserializeObject<foo>(File.ReadAllText(someJsonString);

This allows me to read in a JSON file and convert it to a C# object. But now I would like to write this object out to JSON but change the format to be this:

{
    "property_a":.098
}

I currently have another class that is identical and the only difference is that I change the JsonProperty field to the new desired name:

public class foo {
    [JsonProperty("property_a")]
    public decimal PropertyA{ get; set; }
}

Is there a way using Newtonsoft to have a JsonProperty read as a particular value but write as a different?

Josh
  • 10,352
  • 12
  • 58
  • 109
  • You can use a custom contract resolver for this. See for instance [JsonProperty WebApi request and response models](https://stackoverflow.com/a/34365216/3744182) and [Json.NET deserialize or serialize json string and map properties to different property names defined at runtime](https://stackoverflow.com/q/38111298/3744182). In fact I think this is a duplicate, agree? – dbc Oct 28 '22 at 20:06

0 Answers0