【发布时间】:2015-03-25 22:45:44
【问题描述】:
所以我有一个 JSON 文件,其中嵌套了一个对象。它看起来像这样:
{ "MyObject" : { "prop1": "Value1", "prop2" : "Value2"}
"Message" : "A message"}
有时,嵌套在 JSON 中的对象可能为空。比如,
{ "MyObject" : null
"Message" : "A message"}
我正在尝试使用 Newtonsoft.Json 将此对象反序列化为一个具有两个属性的对象(我们称之为 JsonObject):“MyObject”和“Message”。 Message 只是一个字符串,但 MyObject 是一个具有一些其他(私有)属性以及构造函数的对象:
public class MyObject
{
public MyObject(string prop1, string prop2)
{
this.prop1= prop1;
this.prop2= prop2;
}
public string prop1 { get; private set; }
public string prop2 { get; private set; }
JsonObject 看起来像这样:
public class JsonObject
{
public MyObject MyObject { get; set; }
public string Message { get; set; }
}
我的反序列化代码如下所示:
using (StreamReader reader = new StreamReader(filename))
{
string jsonFile = reader.ReadToEnd();
return JsonConvert.DeserializeObject<JsonObject>(jsonFile);
}
但是它抛出了一个错误:
Exception: Object reference not set to an instance of an object
当 MyObject 对象为空时会发生这种情况。我打印了 jsonFile,这是输出:
{"MyObject": null, "Message": "sample message"}
我想要的是让 MyObject 反序列化为 null。因此,当代码运行时,最终结果是 MyObject = null 且 Message = "sample message" 的 JsonObject。如何使用 Newtonsoft.Json 执行此操作?
【问题讨论】:
-
您的 JSON 格式不正确 - 您需要在两个根对象属性之间使用逗号。 IE。
{ "MyObject" : { "prop1": "Value1", "prop2" : "Value2"}, "Message" : "A message"}和{ "MyObject" : null, "Message" : "A message"}。解决了这个问题后,我可以成功反序列化两个 JSON 字符串。你能把你的问题写成Minimal, Complete, and Verifiable example吗?
标签: c# json json.net deserialization