0

I have a JObject that I am trying to add fields to in a way like this:

JObject dataObject = new JObject();
dataObject[currentSection][key] = val;

currentSection, key and val are all strings, I want it so when its all serialized at the end that it looks something like this:

{
    "currentSection": {
        "key": "value"
    }
}

How would I go about doing this?

2 Answers 2

1

You can use JObject.Add() method to add a property to JObject.

  1. Create a JObject for the nested object.

  2. Add property to the nested object.

  3. Add property with nested object to root JObject.

JObject dataObject = new JObject();
        
JObject nestedObj = new JObject();
nestedObj.Add(key, val);

dataObject.Add(currentSection, nestedObj);

Demo @ .NET Fiddle

Sign up to request clarification or add additional context in comments.

Comments

1

You have one nested json object inside of the another one. So you have to create a nested currentSection json object before assigning a key to currrentSection

    string currentSection = "currentSection";
    string key = "key";
    string val = "val";

    JObject dataObject = new JObject();
    dataObject[currentSection] = new JObject();
    dataObject[currentSection][key] = val;  

or you can do the same in one line

var dataObject = new JObject { [currentSection] = new JObject { [key] = val } };

json

var json = dataObject.ToString();

{
  "currentSection": {
    "key": "val"
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.