jollyroger23 jollyroger23 - 5 months ago 22
JSON Question

Double Label for Json Property C#

I need to pass a Json object to an API, but the API requires the Json properties to have a double label of sorts, such as:

{
"name:id":"1234"
}


However, using Newtonsoft.Json.Linq, I can't get this to format the label exactly. Here is what I've tried so far (which throws an error)

dynamic json= new JObject();
json.name.id = "1234";


Doing

json.id = "1234";


Works just fine. I have also tried

json.name = new JProperty("id", "1234");


Which also throws an error. I have also tried hard coding the json file as a single string and converting that to a JObject, which also threw an error. Is what I'm trying to do possible or am I missing something? Is there another Json package I could use that would support what I want to do?

Answer

Use JObject's string indexer notation.

dynamic json = new JObject();
json["name.id"] = "1234";

Since the json is essentially built as a key/value pair, using a string indexer can allow you to overcome atypical property names.

Comments