序列化C#对象并保留属性名
我正在尝试将序列化对象发布到web服务。该服务要求将属性名“context”和“type”格式化为“@context”和“@type”,否则它将不接受该请求 Newtonsoft JSON.NET正在从属性名“context”和“type”中删除“@”,我需要将它们带到JSON中。有人能帮忙吗 这是我正在使用的类序列化C#对象并保留属性名,c#,json,json.net,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 @t
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>();
}
但这就是我需要它序列化的地方:
{
"potentialAction": [
{
"@context": "http://schema.org",
"@type": "ViewAction",
"name": "View in Portal",
"target": [
"http://www.example.net"
]
}
]
}
在C#中,用于允许您使用保留字,例如@class
。因此,它将被有效地忽略。要控制序列化的属性名称,需要将属性添加到模型中:
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>();
}
公共类潜在作用
{
[JsonProperty(“@context”)]
公共字符串@context{get;set;}
[JsonProperty(“@type”)]
公共字符串@type{get;set;}
公共字符串名称{get;set;}
公共IList目标{get;set;}=new List();
}
在C#中,用于允许您使用保留字,例如@class
。因此,它将被有效地忽略。要控制序列化的属性名称,需要将属性添加到模型中:
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>();
}
公共类潜在作用
{
[JsonProperty(“@context”)]
公共字符串@context{get;set;}
[JsonProperty(“@type”)]
公共字符串@type{get;set;}
公共字符串名称{get;set;}
公共IList目标{get;set;}=new List();
}
有一些属性可用于定义字段名称
您可以这样使用它:
[JsonProperty(PropertyName=“@context”)]
公共字符串上下文{get;set;}
有一些属性可用于定义字段名称
您可以这样使用它:
[JsonProperty(PropertyName=“@context”)]
公共字符串上下文{get;set;}
请注意,C#code中的@
实际上并不被视为标识符的一部分,因此这些属性的名称实际上是上下文
和类型
。@用于告诉编译器,任何语法规则都会使下面的单词A关键字被忽略,并将其视为标识符,但是<代码> @ <代码>不会添加到标识符中。换句话说,不是Json.Net删除了@
,而是C#编译器没有添加它们,因为它们意味着其他东西。请注意,C#代码中的@
实际上并不被视为标识符的一部分,因此这些属性的名称实际上是上下文和类型。@用于告诉编译器,任何语法规则都会使下面的单词A关键字被忽略,并将其视为标识符,但是<代码> @ <代码>不会添加到标识符中。换句话说,不是Json.Net删除了@
,而是C#编译器没有添加它们,因为它们意味着其他东西。谢谢你的回答谢谢你的回答谢谢你的回答谢谢你的回答谢谢你的回答谢谢你的回答