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
dynamicat all? Just use aDictionary<string, object>dynamic. The concrete type Json.NET uses for a JSON object isJObject, 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.Dictionary<string, object>orJObjectin runtime.