【问题标题】:Exception when converting JObject "ToObject"转换 JObject "ToObject" 时出现异常
【发布时间】:2014-06-16 10:09:23
【问题描述】:

我有一个 Post 函数,它接收一个 JObject(Newtonsoft Json) 作为 post 变量。

现在我需要这是一个 JObject,因为我有基于其他信息的“真实类型”,并且我需要额外的灵活性(我不能使用泛型和其他选项)。

现在我正在使用这个代码:

JObject data; // this is assigned with the data from the post.
Type type = getTypeFromSomeWhere(param1);
object obj = data.ToObject(type); // I need this since I reflect the object later on.

我的输入数据如下所示:

{
  "Disclaimer": {},
  "Name": {
    "IsRelevant": true,
    "Value": "Sample Name"
  },
}

我正在尝试将对象转换为这种类型:

public class MyEntity
{
    public string Disclaimer{ get; set; }

    public Field<string> Name{ get; set; } // Field has Value\IsRelevant and other stuff.
}

我遇到了这个异常:

{"Error reading string. Unexpected token: StartObject. Path 'Disclaimer'."}

我试图了解它为什么会发生。对象看起来不错。我猜这是由于空对象免责声明,但我需要支持这些情况。

编辑:
当我在免责声明中插入一个字符串时,一切正常。
我如何告诉他将“null”插入空对象?

【问题讨论】:

  • 免责声明的类型是字符串,您提供的对象就是它给出异常的原因
  • 是的,我完全理解并编辑了。如何将“空对象”作为空值工作?
  • 不要传递任何东西。这将为免责声明插入空值
  • 我太傻了..有人在我的代码中改变了一些东西,这毁了这个..谢谢你的回答!!

标签: c# json serialization json.net


【解决方案1】:

您的映射不正确。免责声明是一个对象,因为它被定义为{}

{
  "Disclaimer": {},  //this is an OBJECT
  "Name": {  
    "IsRelevant": true,
    "Value": "Sample Name"
  },
}

这就是为什么当 JSON.NET 找到 { 并且您尝试将其映射到字符串时收到错误 {"Error reading string. Unexpected token: StartObject. Path 'Disclaimer'."}

至于Name,它也是一个对象。我不知道你的 Field&lt;T&gt; 是什么样子,但只要它有一个 Value 属性,它应该可以工作。

一个正确的模型:

public class Disclaimer
{
}

public class MyEntity
{
    public string Disclaimer{ get; set; }
    public Field<string> Name { get; set; }
}

【讨论】:

  • 我太傻了..有人在我的代码中改变了一些东西,这毁了这个..谢谢你的回答!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
相关资源
最近更新 更多