C# JSON-动态构建JSON

C# JSON-动态构建JSON,c#,json,C#,Json,我试图动态构建json,但似乎无法在动态对象中获得结果来存储值: public class CDJson : JObject { public string id { get; set; } public string style { get; set; } public string @class { get; set; } } public class CDColsJson : JObject {

我试图动态构建json,但似乎无法在动态对象中获得结果来存储值:

    public class CDJson : JObject
    {
        public string id { get; set; }
        public string style { get; set; }
        public string @class { get; set; }
    }
    public class CDColsJson : JObject
    {
        public string id { get; set; }
        public string style { get; set; }
        public string @class { get; set; }
        public int xsCol { get; set; }
        public int smCol { get; set; }
        public int mdCol { get; set; }
        public int lgCol { get; set; }
    }

    public string Build_CDSectionJson(string id, string style, string @class)
    {
        dynamic cdSection = new JObject();
        cdSection.section = new Constants.CDJson() { id = id, style = style, @class = @class };

        string json = JsonConvert.SerializeObject(cdSection); // WHERE THE VALUES ARE EMPTY

        return json;
    }
代码:

输出:

    {"section":{}}
我正在传递一些值,但它们是空的,我做错了什么

我试过这个:

    dynamic cdSection = new JObject();
    cdSection.section.id = id;
    cdSection.section.style = style;
    cdSection.section.@class = @class;
但返回为空。

谢谢JLRishe

这非常有效:

    JObject cdSectionAttr = new JObject();
    cdSectionAttr.Add("id", id);
    cdSectionAttr.Add("style", style);
    cdSectionAttr.Add("@class", @class);

    JObject cdSection = new JObject();
    cdSection.Add("section", cdSectionAttr);

你为什么要继承JObject?这可能就是原因。还要看看我需要的json,如{“section”:{“id”:“dgdhdjhf”,“style”:“somestyle”,“class”:“somesclass”}。如何实现这一点?您不应该将
cdSection
a
dynamic
或为其指定任意的C类型属性。如果要将属性添加到
JObject
,请使用
cdSection.add(“section”,theValue)
另外,您在这里实际要做的是什么?为什么不定义一个具有
CDJson
类型的
section
属性的类呢?
    JObject cdSectionAttr = new JObject();
    cdSectionAttr.Add("id", id);
    cdSectionAttr.Add("style", style);
    cdSectionAttr.Add("@class", @class);

    JObject cdSection = new JObject();
    cdSection.Add("section", cdSectionAttr);