Saturday, June 23, 2018

Converting JsonValue to domain object

Leave a Comment

I have an API call as listed below:

JsonValue result = api.GET("/chart/" + problemList.PatientMRN.ToString() + "/problems", problemInfo); string resultString = result.ToString(); 

Note: I am referring to System.Json.JsonValue

Alternative Approach (using JavaScriptSerializer )

Rootobject_Labresult objGResponse = new JavaScriptSerializer().Deserialize<Rootobject_Labresult>(resultString); 

From the string in Json, I created corresponding classes (using Paste Special in Visual Studio edit menu).

public class Rootobject_Labresult {     public Labresult[] labresults { get; set; }     public int totalcount { get; set; } }  public class Labresult {     public string createddate { get; set; }     public DateTime createddatetime { get; set; }     public string departmentid { get; set; }     public string description { get; set; } } 

But when I create an array, I am getting following error.

Labresult[] labresults = result[0];   ////Error: cannot implicitly convert type System.Json.JsonValue to Labresult 

What is the best way to convert JsonValue to the domain object (Labresult) ?

2 Answers

Answers 1

This could have also been done simpler using Json.Net

JsonConvert.DeserializeObject<T> Method (String)

//...code removed for brevity string json = result.ToString(); Rootobject_Labresult rootObject = JsonConvert.DeserializeObject<Rootobject_Labresult>(json); Labresult[] labresults = rootObject.labresults; 

From there you should be able to extract the desired domain values.

And as simple as that was you could have created an extension

public static class JsonValueExtensions {     public static T ToObject<T>(this JsonValue value) {         return JsonConvert.DeserializeObject<T>(value.ToString());     } } 

which reduces the original code even further

//...code removed for brevity Rootobject_Labresult rootObject = result.ToObject<Rootobject_Labresult>(); Labresult[] labresults = rootObject.labresults; 

The assumption being that result in the above snippet example is an instance of JsonValue

Answers 2

I believe the best way to convert from string/System.Json.JsonValue to DotNet Object using Json.NET

All you need is the Newtonsoft.Json.Linq namespace and you can do all the conversation with single line of code

using Newtonsoft.Json.Linq;  var result = JToken.Parse(jsonVal.ToString()).ToObject<Rootobject_Labresult>(); 

I have created a example here. https://dotnetfiddle.net/N2VfKl

Here is another example for object conversation using Json.NET https://dotnetfiddle.net/rAkx7m

Json.Net also allow you to work with the json object without declare the class. https://dotnetfiddle.net/ZIA8BV

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment