简体   繁体   English

C# - 从属性名称中带有“System”的 JSON 对象中提取值

[英]C# - extracting values from JSON object with "System" in property names

At the beginning I want to say that 'm not a C# developer by any means, however at my work I've received a task where I have to write simple web service in .net.一开始我想说无论如何我都不是 C# 开发人员,但是在我的工作中,我收到了一项任务,我必须在 .net 中编写简单的 Web 服务。 The task is not very complicated however I've encountered the problem that JSON payload which is sent to our web service has "System" in property names:该任务并不是很复杂,但是我遇到了发送到我们的 Web 服务的 JSON 有效负载在属性名称中具有“系统”的问题:

"resource": {
        "fields": {
            "System.AreaPath": "someData",
            "System.TeamProject": "someData",
            "System.IterationPath": "someData"
         }
}

I'm trying to get those values by using:我正在尝试使用以下方法获取这些值:

    public class Resource
    {
        public Fields System.AreaPath { get; set; }
    }

However I'm getting an error ("System" is a namespace but used like a type.) Are there any best practices on how to perform such task ?但是,我收到一个错误(“System”是一个命名空间,但用作类型。)是否有关于如何执行此类任务的最佳实践? Thank you.谢谢你。

One easy option it to specify the JSON property in an attribute.一个简单的选择是在属性中指定 JSON 属性。 If you're using Json.NET you can use [JsonProperty] for this.如果您使用的是 Json.NET,则可以为此使用[JsonProperty] Complete example:完整示例:

using System;
using System.IO;
using Newtonsoft.Json;

public class Fields
{
    [JsonProperty("System.AreaPath")]
    public string AreaPath { get; set; }

    [JsonProperty("System.TeamProject")]
    public string TeamProject { get; set; }

    [JsonProperty("System.IterationPath")]
    public string IterationPath { get; set; }
}

public class Resource
{
    public Fields Fields { get; set; }
}


class Program
{
    static void Main()
    {
        string json = File.ReadAllText("test.json");
        var resource = JsonConvert.DeserializeObject<Resource>(json);
        Console.WriteLine(resource.Fields.TeamProject);
    }
}

JSON (removed the "resource" part to make it a complete JSON document; I assume you know how to handle this if necessary): JSON(删除了“资源”部分以使其成为一个完整的 JSON 文档;如果需要,我假设您知道如何处理此问题):

{
    "fields": {
        "System.AreaPath": "someData",
        "System.TeamProject": "team project",
        "System.IterationPath": "someData"
     }
}

Output: team project输出: team project

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM