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:
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 ?
it is easy, JArray myarray = new JArray(); JObject myobj = new JObject(); // myobj.
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.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
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" });
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,}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With