I have a a JObject and I would like to set a property from a strongly typed object on it.
JObject["ProductionVersion"] = new ProductionVersion();
In order to do this, ProductVersion needs to be converted to a JToken. How can I do this without having to serialize and deserialize the object as a JObject?
JObject["ProductVersion"] = JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(message.ProductVersion))
JToken is the abstract base class of JObject , JArray , JProperty , and JValue , which represent pieces of JSON data after they have been parsed. JsonToken is an enum that is used by JsonReader and JsonWriter to indicate which type of token is being read or written.
So you see, a JObject is a JContainer , which is a JToken . Here's the basic rule of thumb: If you know you have an object (denoted by curly braces { and } in JSON), use JObject.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
Your question is a bit confusing..
JObject
and you want a JToken
?
Well, a JObject
is a JToken
. Take a look at the inheritance hierarchy here: JObject class
JToken.FromObject(obj)
You can access the properties by calling Properties
on the JObject
.
When you need to add a property, just add it using the JProperty
constructor.
See the JSON.NET documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With