道歉,如果早些时候被问过,但我在这方面找不到太多,因此请问这里。
我需要在我的REST请求JSON有效负载中保留我的案例。 我使用了JsonProperty,但确实有帮助。
我有一个对应于JSON POST请求有效负载的类:
namespace AugmentedAi.Common
{
[Serializable]
public class InstallSoftwareMetadata
{
[JsonProperty(propertyName:"sourceType")]
public string SourceType { get; set; }
[JsonProperty(propertyName: "toolInstance")]
public string ToolInstance { get; set; }
public static InstallSoftwareMetadata GetInstallSoftwareMetadata()
{
var ticketDetail = new TicketDetail
{
Switch = "/easy",
Number = Guid.NewGuid().ToString()
};
return new InstallSoftwareMetadata
{
SourceType = "rest1",
ToolInstance = "rest1",
TicketDetail = ticketDetail
};
}
}
}
public class TicketDetail
{
[JsonProperty("number")]
public string Number { get; set; }
[JsonProperty("Switch")]
public string Switch { get; set; }
}
由于案例不匹配,我从服务器收到异常。 在异常消息中,我可以看到所有请求参数都已序列化为小写。
这有什么用?请建议
编辑: 这就是我发送REST请求的方式。 PostJsonAsync正在序列化它。
var installSoftwarResponse = await baseUrl.WithHeader("Accept", "application/json")
.WithHeader("Content-Type", "application/json") .PostJsonAsync(InstallSoftwareMetadata.GetInstallSoftwareMetadata())
.ReceiveJson<InstallSoftwareResponse>();
答案 0 :(得分:0)
使用JSON.NET你会这样做并注意你不需要[Serializable]属性
void Main()
{
var res = JsonConvert.SerializeObject(InstallSoftwareMetadata.GetInstallSoftwareMetadata());
}
public class InstallSoftwareMetadata
{
[JsonProperty("sourceType")]
public string SourceType { get; set; }
[JsonProperty("toolInstance")]
public string ToolInstance { get; set; }
[JsonProperty("ticketDetail")]
public TicketDetail TicketDetail { get; set; }
public static InstallSoftwareMetadata GetInstallSoftwareMetadata()
{
var ticketDetail = new TicketDetail
{
Switch = "/easy",
Number = Guid.NewGuid().ToString()
};
return new InstallSoftwareMetadata
{
SourceType = "rest1",
ToolInstance = "rest1",
TicketDetail = ticketDetail
};
}
}
public class TicketDetail
{
[JsonProperty("number")]
public string Number { get; set; }
[JsonProperty("Switch")]
public string Switch { get; set; }
}
结果
{
"sourceType": "rest1",
"toolInstance": "rest1",
"ticketDetail": {
"number": "2c8b5d48-315e-406c-ad4f-b07922fdd135",
"Switch": "/easy"
}
}