亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

序列化 C# 對象并保留屬性名稱

序列化 C# 對象并保留屬性名稱

C#
烙印99 2022-01-09 17:40:12
我正在嘗試將序列化對象發布到 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>();

}


查看完整回答
反對 回復 2022-01-09
?
慕森王

TA貢獻1777條經驗 獲得超3個贊

您可以使用一些屬性來定義字段名稱應該是什么。

https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm

你會像這樣使用它: [JsonProperty(PropertyName = "@context")] Public string context { get; set ; }


查看完整回答
反對 回復 2022-01-09
  • 2 回答
  • 0 關注
  • 304 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號