使用C#对象创建复杂的JSON

我正在尝试从保存数据的c#对象创建json。 数据采用简单的表格格式。由列组成:名称,InputCode,DisplayID,CodeID,ParentID。 如果Parent(Net),则ParentID为null。如果为Children(Subnet),则具有ParentID,该ParentID包含Parent(Net)的CodeID。 CodeID是唯一的。 我在使用foreach的子网下面临迭代问题。它不允许。

public class CodeFrameJson
    {
        public string Name { get; set; }
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public int? InputCodeValue { get; set; }
        public int DisplayId { get; set; }
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public List<CodeFrameJson> Subnet { get; set; }
    }
List<CodeFrameJson> cfj = new List<CodeFrameJson>();
            IEnumerable<CodeDTO> _cfd = new List<CodeDTO>();
            _cfd = codeFrameJson.getcodeFrame(questionId,projectName);
            _cfd = _cfd.OrderBy(a => a.DisplayOrderNo).ToList();
            foreach (var a in _cfd)
            {
                int CodesID = 0;
                CodeFrameJson obj = new CodeFrameJson();
                if (a.InputCodeValue == null)
                {
                    var root = new CodeFrameJson()
                    {
                        Name = a.CodeName,DisplayId = a.DisplayOrderNo,InputCodeValue = null,Subnet = new List<CodeFrameJson>()
                        {
                            //Start: Not allowing foreach
                            foreach (var x in _cfd)
                            {
                                if (x.ParentId == CodesID)
                                {
                                    new CodeFrameJson()
                                    {
                                        Name = x.CodeName,InputCodeValue = x.InputCodeValue,DisplayId = x.DisplayOrderNo
                                    };
                                }
                            }
                    //End: Not allowing foreach
                }
            };
                    obj = root;
                }
                else {
                    var root = new CodeFrameJson()
                    {
                        Name = a.CodeName,InputCodeValue = a.InputCodeValue,Subnet = null
                    };
                    obj = root;
                }
                cfj.Add(obj);
            }
            var json = JsonConvert.SerializeObject(cfj,Formatting.Indented);

最终输出类似这样的东西很容易区分

{
  "Site": {
    "Name": "Site","DisplayID": 1,"Subnet": [
      {
        "Name": "Full Site","InputCodeValue": 1,"DisplayId": 2
      },{
        "Name": "Partial Site","InputCodeValue": 2,"DisplayId": 3
      }
    ]
  },"Test": {
    "Name": "Test1","InputCodeValue": 3,"DisplayId": 4
  }
}
ft2015250 回答:使用C#对象创建复杂的JSON

这实际上不需要使用JSON进行任何操作,而是使用对象(集合)初始化。您只能在此处分配值,但LinQ可以解决:

只需过滤列表并在select语句中创建新对象:

Subnet = _cfd.Where(x => x.ParentId == CodesID).Select(x => new CodeFrameJson
{
    Name = x.CodeName,InputCodeValue = x.InputCodeValue,DisplayId = x.DisplayOrderNo
}).ToList()
本文链接:https://www.f2er.com/3146327.html

大家都在问