【问题标题】:Using Json.net with Jira's custom fields将 Json.net 与 Jira 的自定义字段一起使用
【发布时间】:2014-06-02 07:04:27
【问题描述】:

要使用 json.net 将对象序列化为 json,我需要创建带有为每个 json 属性标记的属性的 POCO:

public class Priority
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("iconUrl")]
    public string IconUrl { get; set; }
}

我正在使用它与 Jira 的 REST API 进行交互,它适用于所有标准字段。不幸的是,自定义字段是出错的地方。自定义字段没有确定的字段名称,而是分配给它们的数字。因此,如果我有一个“Resolution Type”自定义字段,该属性将不会被称为“ResolutionType”,而是“customfield_10200”。

我正在处理具有相同自定义字段的多个部署,但它们都有不同的字段 ID。我想做的是这样的:

[JsonProperty(ConfigurationManager.AppSettings["JiraResolutionTypeId"])]
public string ResolutionType{ get; set; }

但是你只能在这样的属性中使用编译时常量,所以我不能以这种方式动态设置 id。

我怎样才能解决这个问题?

【问题讨论】:

标签: c# json.net jira-rest-api


【解决方案1】:

使用custom contract resolver 应该可以让您轻松完成此操作。添加您自己的 Attribute 类可以让您以通用方式进行操作。

// add attribute so this only targets properties, or whatever you want
public class JiraAttribute : Attribute
{
    public string LookupId { get; private set; }
    public JiraAttribute(string lookupId)
    {
        this.LookupId = lookupId;
    }
}
public class JiraContractResolver : DefaultContractResolver
{
    public static readonly JiraContractResolver Instance = new JiraContractResolver();

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        var attr = member.GetCustomAttributes(typeof(JiraAttribute), true).Cast<JiraAttribute>().ToList();
        if (attr != null && attr.Count > 0)
        {
            property.PropertyName = ConfigurationManager.AppSettings[attr[0].LookupId];
        }

        return property;
    }
}

// in a class
[Jira("JiraResolutionTypeId")]
public string ResolutionType { get; set; }

//e.g.
// ConfigurationManager.AppSettings["JiraResolutionTypeId"] == "customfield_10200"
var settings = new JsonSerializerSettings { ContractResolver = JiraContractResolver.Instance };
var s = JsonConvert.SerializeObject(new Priority { Id = "123", ResolutionType = "abc" }, settings);
// {"id":"123","name":null,"iconUrl":null,"customfield_10200":"abc"}
var d = JsonConvert.DeserializeObject<Priority>(s, settings);
// d.ResolutionType == "abc"

【讨论】:

    【解决方案2】:

    这里记录了另一种方法。 http://www.31a2ba2a-b718-11dc-8314-0800200c9a66.com/2016/01/a-simple-approach-to-getting-all-of.html

    获取 Json 请求,转换为 XML,保存在 SQL Server 中,然后使用自定义函数从自定义 JIRA 字段中提取您需要的任何内容。

    【讨论】:

    • 为什么有人会点击那个网址名称?
    • 请在此处的回答中包含相关信息。另外,链接到您自己的博客时,请说这是您的博客。否则可能会被视为垃圾邮件。见:How to not be a spammer
    • 欢迎来到 Stack Overflow!请阅读meta.stackexchange.com/questions/141589 的答案中链接到您的个人博客的指南。为了符合这些准则,应更新此答案,以便用户无需点击博客文章即可解决问题。另外,请确保您不要养成总是链接到您的博客的习惯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    相关资源
    最近更新 更多