将JsonValue转换为域对象

LCJ*_*LCJ 4 .net c# json.net

我有一个API调用,如下所示:

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

注意:我指的是System.Json.JsonValue

替代方法(使用JavaScriptSerializer)

Rootobject_Labresult objGResponse = new JavaScriptSerializer().Deserialize<Rootobject_Labresult>(resultString);
Run Code Online (Sandbox Code Playgroud)

从Json中的字符串,我创建了相应的类(使用Visual Studio编辑菜单中的Paste Special).

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; }
}
Run Code Online (Sandbox Code Playgroud)

但是当我创建一个数组时,我得到了以下错误.

Labresult[] labresults = result[0];  
////Error: cannot implicitly convert type System.Json.JsonValue to Labresult
Run Code Online (Sandbox Code Playgroud)

JsonValue转换为域对象(Labresult)的最佳方法是什么?

Nko*_*osi 15

使用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;
Run Code Online (Sandbox Code Playgroud)

从那里你应该能够提取所需的域值.

就这么简单,你可以创建一个扩展

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

这进一步减少了原始代码

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

假设result在上面的代码段示例中是一个实例JsonValue