Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object of any type to JObject with Json.NET

Tags:

c#

.net

json.net

I often need to extend my Domain model with additional info before returning it to the client with WebAPI. To avoid creation of ViewModel I thought I could return JObject with additional properties. I could not however find direct way to convert object of any type to JObject with single call to Newtonsoft JSON library. I came up with something like this:

  1. first SerializeObject
  2. then Parse
  3. and extend JObject

Eg.:

var cycles = cycleSource.AllCycles();  var settings = new JsonSerializerSettings {     ContractResolver = new CamelCasePropertyNamesContractResolver() };  var vm = new JArray();  foreach (var cycle in cycles) {     var cycleJson = JObject.Parse(JsonConvert.SerializeObject(cycle, settings));     // extend cycleJson ......     vm.Add(cycleJson); }  return vm; 

I this correct way ?

like image 701
dragonfly Avatar asked Feb 24 '14 14:02

dragonfly


People also ask

How do I convert JArray to JObject?

it is easy, JArray myarray = new JArray(); JObject myobj = new JObject(); // myobj.

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.

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

JObject implements IDictionary, so you can use it that way. For ex,

var cycleJson  = JObject.Parse(@"{""name"":""john""}");  //add surname cycleJson["surname"] = "doe";  //add a complex object cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" }); 

So the final json will be

{   "name": "john",   "surname": "doe",   "complexObj": {     "id": 1,     "name": "test"   } } 

You can also use dynamic keyword

dynamic cycleJson  = JObject.Parse(@"{""name"":""john""}"); cycleJson.surname = "doe"; cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" }); 
like image 157
L.B Avatar answered Oct 05 '22 11:10

L.B


If you have an object and wish to become JObject you can use:

JObject o = (JObject)JToken.FromObject(miObjetoEspecial); 

like this :

Pocion pocionDeVida = new Pocion{ tipo = "vida", duracion = 32, };  JObject o = (JObject)JToken.FromObject(pocionDeVida); Console.WriteLine(o.ToString()); // {"tipo": "vida", "duracion": 32,} 
like image 37
Condemateguadua Avatar answered Oct 05 '22 09:10

Condemateguadua