首页 > 解决方案 > 如何将特定类型的 JSON 响应转换为另一个 JSON 响应?

问题描述

我有一个现有的 JSON 响应,看起来像,

{"rarautomation":{"stable":{"ixRepo":"100024"}},"crmweb":{"stable":{"ixRepo":"100028"},"release":{"ixRepo":"101543"}},"models":{"stable":{"ixRepo":"100341"},"PhaseOutDefaultModel":{"ixRepo":"102088"},"FfwModelUpdate2017Q4":{"ixRepo":"102258"},"SsiQ42017":{"ixRepo":"102266"}}}

我已经编写了 ac# 代码来获取新的 JSON 响应,就像,

var repoList = new Dictionary<string, List<string>>();

tempList.Add("master");

tempList.Add("release");

repoList["IdentifyApplicationDataService"] = tempList;

我将此字典作为 JSON 响应返回,看起来像

"IdentifyApplicationDataService":["master","release"],"CallLogger":["master"],"UniversalPackagingSystem":["master"]}

我应该如何修改我的 C# 表示以获得像我的第一个 JSON 响应这样的响应?

标签: c#json

解决方案


你可以像这样为你的班级建模

public class IxData
        {
            public string IxRepo { get; set; }
        }

        public class DeviceData
        {
            public Dictionary<string, IxData> Models { get; set; }
            public Dictionary<string, IxData> CrmWeb { get; set; }
            public Dictionary<string, IxData> Rarautomation { get; set; }
        }

并像这样使用它

 var device = new DeviceData
            {

                CrmWeb = new Dictionary<string, IxData>
                {
                    {
                        "stable", new IxData
                        {
                            IxRepo = "100028"
                        }
                    },
                    {
                        "release", new IxData
                        {
                            IxRepo = "101543"
                        }
                    }
                },
                Rarautomation = new Dictionary<string, IxData>
                {
                    {
                        "stable", new IxData
                        {

                            IxRepo = "100024"
                        }
                    }
                },
                Models = new Dictionary<string, IxData>
                {
                    {
                        "stable", new IxData
                        {
                            IxRepo = "100341"
                        }
                    },
                    {
                        "PhaseOutDefaultModel", new IxData
                        {
                            IxRepo = "102088"
                        }
                    }
                },
            };

            var json = JsonConvert.SerializeObject(device, new JsonSerializerSettings()
            {

                Formatting =  Formatting.Indented,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

输出是 在此处输入图像描述


推荐阅读