gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:21:22 25 4
gpt4 key购买 nike

我正在尝试将序列化对象发布到 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>();
}

这是它被转换成的 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"
]
}
]
}

最佳答案

在 C# 中,@ prefix on a variable用于允许您使用保留字,例如 @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>();
}

关于c# - 序列化 C# 对象并保留属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52255593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com