1

I am trying to build my json dynamically but cant seem to get the results within the dynamic object to store the values:

    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;
    }

Code:

    var CD_Section = build.Build_CDSectionJson(sectionGUID, "", "sectioncon")

Output:

    {"section":{}}

I am passing some values but they are empty, what am i doing wrong?

I tried this:

    dynamic cdSection = new JObject();
    cdSection.section.id = id;
    cdSection.section.style = style;
    cdSection.section.@class = @class;

But came back as null.

4
  • 1
    Why would you inherit JObject? That may be why. Also take a look at newtonsoft.com/json/help/html/CreateJsonDynamic.htm Commented Dec 8, 2019 at 12:38
  • i need the json like this {"section":{ "id" : "dgdhdjhf", "style" : "somestyle", "class" : "someclass" }}. how would i achieve this? Commented Dec 8, 2019 at 12:46
  • 1
    You should not make cdSection a dynamic or assign arbitrary C#-type properties to it. If you want to add a property to a JObject, use cdSection.Add("section", theValue) Commented Dec 8, 2019 at 12:54
  • Also, what is it that you're actually trying to do here? Why not define a class that has a section property of type CDJson? Commented Dec 8, 2019 at 12:56

1 Answer 1

1

Thanks JLRishe

This worked great:

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

    JObject cdSection = new JObject();
    cdSection.Add("section", cdSectionAttr);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.