Reputation: 5
I want to deserialize model correctly and change properties name on serializing with Newtonsoft. Is it possible?
public class AccountingInspectionsResponseModel
{
[JsonProperty("subject_data")]
public OrganizationInfo OrganizationInfo { get; set; }
[JsonProperty("inspections")]
public List<InspectionInfo> Inspections { get; set; }
}
Upvotes: 0
Views: 437
Reputation: 1202
You can't just rename properties. You will need to remap your object to a new model and then re-serialize it.
Here is a working .netFiddle
Here is the code
public class DeserializeModel
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("greetings")]
public string Greetings { get; set; }
}
public class SerializeModel
{
public SerializeModel(string name, string greets)
{
this.WhatsMyName = name;
this.Greets = greets;
}
public string WhatsMyName { get; set; }
public string Greets { get; set; }
}
public class Program
{
public static string json = @"{name:'John', greetings:'hello'}";
public static void Main()
{
var deserialized = JsonConvert.DeserializeObject<DeserializeModel>(json);
Console.WriteLine(JsonConvert.SerializeObject(deserialized));
var mappedData = MapToSerializeModel(deserialized);
Console.WriteLine(JsonConvert.SerializeObject(mappedData));
}
public static SerializeModel MapToSerializeModel(DeserializeModel d)
{
return new SerializeModel(d.Name, d.Greetings);
}
}
Upvotes: 1