我正在嘗試將序列化對象發布到 Web 服務。該服務要求將屬性名稱“context”和“type”格式化為“@context”和“@type”,否則它不會接受請求。Newtonsoft JSON.NET 正在從屬性名稱“上下文”和“類型”中刪除“@”,我需要將它們傳遞到 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>();}這是它被轉換為的 JSON:{ "potentialAction": [ { "context": "http://schema.org", "type": "ViewAction", "name": "View in Portal", "target": [ "http://www.example.net" ] } ]}但這就是我需要將其序列化為:{ "potentialAction": [ { "@context": "http://schema.org", "@type": "ViewAction", "name": "View in Portal", "target": [ "http://www.example.net" ] } ]}
2 回答

揚帆大魚
TA貢獻1799條經驗 獲得超9個贊
在 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>();
}

慕森王
TA貢獻1777條經驗 獲得超3個贊
您可以使用一些屬性來定義字段名稱應該是什么。
https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm
你會像這樣使用它: [JsonProperty(PropertyName = "@context")]
Public string context { get; set ; }
- 2 回答
- 0 關注
- 304 瀏覽
添加回答
舉報
0/150
提交
取消