是否建议甚至可能将Pascal Case JSON字符串转换为Camel Case JSON?
我知道如何将有效载荷反序列化为对象,然后再将其序列化为字符串,但这不是我现在想要的。
到目前为止,我已经这样做了:
JsonSerializerOptions jsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase};
var pascalPayload = "{"Id":"1","Type":"Confectionary"}";
var camelCasePayload = JsonSerializer.Serialize(pascalPayload, jsonOptions)
我在这里看到的问题是它包含以下字符,我没有预料到这一点,而且我的属性没有序列化为camelcase。例如
{u0022Id:u00221u0022,....
我是否从序列化选项中遗漏了一些东西,因为我期望这作为输出:
"{"id":"1","type":"Confectionary"}";
传递给Serialize的是字符串而不是对象。这是将json字符串序列化为字符串值....
你需要像这样传递一个对象:
首先声明一个类:
public class MyPayload
{
public string Id { get; set; }
public string Type { get; set; }
}
然后你的代码:
JsonSerializerOptions jsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase};
//notice we create an instance and pass that to Serialize
var pascalPayload = new MyPayload { Id = "1", Type = "Confectionary"};
var camelCasePayload = JsonSerializer.Serialize(pascalPayload, jsonOptions);
没有办法绕过它使用JsonSerializer....如果你不想使用对象,那么你需要自己操作字符串。