2

I am trying to create a JObject on the fly for unit testing but it does not seem to like name.subname as a property

The json that I am trying to create JObject for is

   { "UserDetails": {
          "FirstName": "Test1",
          "Surname": "Test2",
          "UserID": "123456789",
          "Children1.Active1": false,
          "Children1.Active2": false
    }
}

The C# code I have is

dynamic jsonObject = new JObject();
jsonObject.UserDetails = new JObject();
jsonObject.UserDetails.UserID = "123456789";
jsonObject.UserDetails.FirstName = "Test1";
jsonObject.UserDetails.Surname= "Test2";

However i am not sure how to add Children1.Active to the JObject jsonObject. UserDetails it does not work with jsonObject.UserDetails.Children.Active1 = false.

I have validated the json and it passes validation for being valid json.

How can I add Children1.Active to JObject?

I have tried jsonObject.UserDetails.Children1 = new JObject(); But this creates a new sub object which is not what I need.

dbc
  • 104,963
  • 20
  • 228
  • 340
Inkey
  • 2,189
  • 9
  • 39
  • 64
  • Sounds like `Children1` needs to be an array or object itself. That's not a good JSON schema. As for the question itself, *instead* of trying to access `JObject` as a dynamic object, use its own properties and set properties and keys. You don't need `dynamic` in *this* code anyway - store the `UserDetails` object in a separate variable and you won't need to access it through `jsonObject` – Panagiotis Kanavos Oct 05 '18 at 10:36

1 Answers1

3

"Children1.Active2" isn't a nested object, it's a property with a period in the name string. And since you're doing everything via dynamic, this becomes a nuisance, as c# identifiers can't include such a character even though JSON property names can.

In such cases, instead of using dynamic, it's easier to do things with a typed JObject and its compile-time-bound methods, specifically its string indexer method:

var jsonObject = new JObject();
var userDetails = new JObject();
jsonObject["UserDetails"] = userDetails;
userDetails["UserID"] = "123456789";
userDetails["FirstName"] = "Test1";
userDetails["Surname"] = "Test2";           
userDetails["Children1.Active1"] = false;
userDetails["Children1.Active2"] = false;

This should also be more performant as dynamic can have some run-time performance penalties.

Sample fiddle here.

dbc
  • 104,963
  • 20
  • 228
  • 340