2

I need to add some properties to a json string dynamically. Here is the code I'm using:

// set as empty json object
RequestMessage = "{}";
dynamic d = JsonConvert.DeserializeObject(RequestMessage);
d.Request = JsonConvert.SerializeObject(request);
d.RequestOptions = JsonConvert.SerializeObject(requestOptions);
RequestMessage = JsonConvert.SerializeObject(d);

This can add Request and RequestOptions to d, then serialize d back to json string.

It works fine if I know the properties' names, in this case, they are Request and RequestOptions.

Question is: is there a way to do this IF the property name is a variable? for example, something like:

private string GetJson(string name, object obj)
{
    // name is "Request"
    // object is request
    ......
    return RequestMessage;
}

Is it possible? *I'm using .net + newton json.

thanks

6
  • 2
    Why use dynamic at all? Just use a Dictionary<string, object> Commented Apr 6, 2020 at 15:39
  • 2
    Don't use dynamic. The concrete type Json.NET uses for a JSON object is JObject, so use that. See: How do you add a JToken to an JObject?, How do you Add or Update a JProperty Value in a JObject. A dictionary as mentioned above would also work. Commented Apr 6, 2020 at 15:40
  • the purpose is to add a property to the object dynamically (the object is converted from a json string), then convert it back to json string Commented Apr 6, 2020 at 15:41
  • 2
    You can add items to a Dictionary<string, object> or JObject in runtime. Commented Apr 6, 2020 at 15:43
  • thanks, dbc. if you added it as an answer, I'll accept it. Commented Apr 6, 2020 at 15:53

1 Answer 1

2

Sure, you can add properties dynamically to a dynamic object:

var RequestMessage = "{}";
dynamic d = JsonConvert.DeserializeObject(RequestMessage);
d.Request = JsonConvert.SerializeObject(new { A = 42 });
d.RequestOptions = JsonConvert.SerializeObject(new { B = 22 });

var name = "SomeMore";
d[name]=11;

RequestMessage = JsonConvert.SerializeObject(d);

{"Request":"{\"A\":42}","RequestOptions":"{\"B\":22}","SomeMore":11}
Sign up to request clarification or add additional context in comments.

3 Comments

Why use dynamic instead of Dictionary<string, object> or JObject?
in this case d actually is a JObject
MAJOR headache saver for me. Thanks!

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.