Alex Spence
Alex Spence

Reputation: 1538

Serialize object to JToken

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))

Upvotes: 16

Views: 23937

Answers (2)

dcastro
dcastro

Reputation: 68670

Your question is a bit confusing..

  1. So you have a JObject and you want a JToken? Well, a JObject is a JToken. Take a look at the inheritance hierarchy here: JObject class
  2. If what you meant is "I have a serializable object, and I want to convert it to a JToken without having to serialize and deserialize it again", then use this JToken.FromObject(obj)

Upvotes: 40

Patrick Hofman
Patrick Hofman

Reputation: 156978

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.

Upvotes: 1

Related Questions