我想正确地反序列化模型,并在使用Newtonsoft进行序列化时更改属性名称。有可能吗?
public class AccountingInspectionsResponseModel
{
[JsonProperty("subject_data")]
public OrganizationInfo OrganizationInfo { get; set; }
[JsonProperty("inspections")]
public List<InspectionInfo> Inspections { get; set; }
}
答案 0 :(得分:1)
您无法重命名属性。您需要将对象重新映射到新模型,然后重新序列化。
这是代码
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);
}
}