问题描述
我正在通过api收到一个json
文件,该json
文件将转换为我无法触摸的类,并且具有约400个属性。 json
用于键名 CamelCase ,而在同一json
中,某些键的格式为 snake_case 。
我当前正在使用System.Text.Json,但需要更改为Newtonsoft.json。
我试图创建一个JsonSnakeCaseNamingPolicy
类(仅将属性名称转换为snake_case),并在JsonSerializerOptions
中使用,如下所示:
var deserializeOptions = new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true,PropertyNamingPolicy = new JsonSnakeCaseNamingPolicy()
};
var flexImport = JsonSerializer.Deserialize<List<FlexImport>>(input.MappedObjectJson,deserializeOptions);
但是 CamelCase 中的属性不会被填充。关于如何实现这种情况有什么想法吗?
此json
示例:
[{\"BatchId\":123,\"Title_Id\":123,\"CurrentNumber\":\"aa705128\",\"address\":\"122 BLACKSGATE EN\",\"curr_interest_rate\":4},{\"BatchId\":2,\"Title_Id\":1,\"CurrentNumber\":\"27705128\",\"address\":\"90 ARMA DR\",\"curr_interest_rate\":5},\"Title_Id\":2,\"CurrentNumber\":\"30877674\",\"address\":\"6485 N SIN CIR\",\"curr_interest_rate\":4}]"
这是目标类的一部分:
public class FlexImport
{
public long BatchId { get; set; }
public long TitleId { get; set; }
public string CurrentNumber { get; set; }
public string Address { get; set; }
public decimal? CurrInterestRate { get; set; }
}
解决方法
使用JSON属性
public class FlexImport
{
public long BatchId { get; set; }
[JsonPropertyName("Title_Id")]
public long TitleId { get; set; }
public string CurrentNumber { get; set; }
[JsonPropertyName("address")]
public string Address { get; set; }
[JsonPropertyName("curr_interest_rate")]
public decimal? CurrInterestRate { get; set; }
}
等等根据需要进行调整。