17

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

2 Answers 2

39

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)
1
  • 1
    Sorry about the confusing question, I updated it to be more clear. JToken.FromObject is what I was looking for. Had some issues with resharper intellisense and didn't see that method. Feb 28, 2014 at 21:44
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.