Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting JsonValue to domain object

Tags:

c#

.net

json.net

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) ?

like image 538
LCJ Avatar asked Dec 04 '22 19:12

LCJ


2 Answers

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

like image 24
teamchong Avatar answered Dec 15 '22 06:12

teamchong


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

like image 130
Nkosi Avatar answered Dec 15 '22 07:12

Nkosi