c# - 如何将 Newton.Json 反序列化通用对象转换为自定义对象?

标签 c# asp.net-mvc json.net

<分区>

我正在使用 Newton 的 Json.Net 将 Json 反序列化为 .NET 对象。我想了解是否可以从一般对象转换为特定对象。

即:

object myObject JsonConvert.DeserializeObject<object>(myJsonValue);

myOrder = (Order)myObject;

代码更多的是描述我的问题。我知道可以这样做:

object myObject JsonConvert.DeserializeObject<order>(myJsonValue);

但由于这是一个辅助函数,所以它不能是“顺序”,而是更一般的东西。

谢谢。

编辑:

获取错误:

Getting Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Order'

最佳答案

我要在这里做一个假设,因为问题不是 100% 清楚,但我想我有一个好主意:

But due to the fact this is a helper function then it could not be "order", but something more general.

您需要向辅助函数添加类型参数:

public class SomeHelper
{
    public T Deserialize<T>(string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }
}

并使用它:

SomeHelper helper = new SomeHelper();
string json = "...";
Order order = helper.Deserialize<Order>(json);

关于c# - 如何将 Newton.Json 反序列化通用对象转换为自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25451622/

相关文章:

c# - 最佳线程队列示例/最佳实践

c# - 如何使用 BeginInvoke C#

asp.net-mvc - 如何在 ASP.NET MVC 中获取另一个用户的配置文件?

c# - ASP.NET Core Web 应用程序 (.NET Framework) 项目模板缺少 System.Web.MVC dll

c# - CollectionView.View.Refresh 上的内存泄漏

c# - WPF DataGrid 验证错误?

asp.net-mvc - Razor MVC 4 中的下拉列表

c# - 等待后任务继续不工作

c# - 使用Newtonsoft如何避免 ":"后的tailing space空间

c# - 找不到命名空间 - 使用 TFS 构建