Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize object to JToken

Tags:

c#

.net

json.net

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))
like image 854
Alex Spence Avatar asked Feb 28 '14 20:02

Alex Spence


People also ask

What is JToken in C#?

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.

Is a JObject a JToken?

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.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


2 Answers

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)
like image 114
dcastro Avatar answered Oct 04 '22 13:10

dcastro


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.

like image 42
Patrick Hofman Avatar answered Oct 04 '22 14:10

Patrick Hofman