序列化C#对象并保留属性名称

Tom*_*ech 1 c# json json.net

我试图将序列化对象发布到Web服务.该服务要求将属性名称'context'和'type'格式化为'@context'和'@type',否则它将不接受该请求.

Newtonsoft JSON.NET正在从属性名称'context'和'type'中删除'@',我需要它们进入JSON.有人可以帮忙吗?

这是我正在使用的课程

public class PotentialAction
{
    public string @context { get; set; }
    public string @type { get; set; }
    public string name { get; set; }
    public IList<string> target { get; set; } = new List<string>();
}
Run Code Online (Sandbox Code Playgroud)

这是它被转换为的JSON:

{
  "potentialAction": [
   {
      "context": "http://schema.org",
      "type": "ViewAction",
      "name": "View in Portal",
      "target": [
        "http://www.example.net"
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

但这是我需要它序列化到:

{
  "potentialAction": [
   {
      "@context": "http://schema.org",
      "@type": "ViewAction",
      "name": "View in Portal",
      "target": [
        "http://www.example.net"
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*idG 6

在C#中,@变量前缀用于允许您使用保留字@class.所以它会被有效地忽略.要控制序列化的属性名称,需要将JsonProperty属性添加到模型中:

public class PotentialAction
{
    [JsonProperty("@context")]
    public string @context { get; set; }

    [JsonProperty("@type")]
    public string @type { get; set; }

    public string name { get; set; }
    public IList<string> target { get; set; } = new List<string>();
}
Run Code Online (Sandbox Code Playgroud)