Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSon.Net JObject.FromObject Vs JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(obj));

I tried looking for the above comparison but couldn't find an answer.

As there are multiple ways to get a JObject (or all child types inheriting from JToken) eg:

Method1

. JObject.FromObject(obj);

Method2

. JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(obj));

would Method1 perform better than Method2 ?

My usecase is related to backing up a set of entities into a text file and restoring it back.

like image 598
maicalal Avatar asked Dec 31 '13 12:12

maicalal


People also ask

What is JsonConvert SerializeObject?

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

What is the use of JsonConvert DeserializeObject?

Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.

What is DeserializeObject?

Deserialization. In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.

What is JsonConvert?

Provides methods for converting between . NET types and JSON types.


2 Answers

This is faster:

JObject.FromObject(obj);

It builds a JObject directly from the object. The other method serializes the object to JSON a JSON string and then parses the JSON to build a JObject.

Documentation: JObject.FromObject

like image 71
James Newton-King Avatar answered Sep 27 '22 18:09

James Newton-King


If you look at the source code here and there, both method use jsonSerializer. So it should be the exact same.

like image 40
Florian F. Avatar answered Sep 27 '22 17:09

Florian F.