Json.net反序列化返回一个空对象
我正在使用下面的代码进行序列化.
I'm using the code below for serialization.
var json = JsonConvert.SerializeObject(new { summary = summary });
summary
是类型为SplunkDataModel
的自定义对象:
summary
is a custom object of type SplunkDataModel
:
public class SplunkDataModel
{
public SplunkDataModel() {}
public string Category { get; set; }
public int FailureCount { get; set; }
public Dictionary<string, SplunkError> FailureEntity { get; set; }
public Dictionary<string, string> JobInfo { get; set; }
public string JobStatus { get; set; }
public int SuccessCount { get; set; }
public List<string> SuccessEntity { get; set; }
public int TotalCount { get; set; }
}
序列化将导致以下JSON:
Serialization results in the JSON below:
{
"summary": {
"Category": "category",
"JobStatus": "Failure",
"JobInfo": {
"Course processing failed": ""
},
"TotalCount": 0,
"SuccessCount": 0,
"FailureCount": 0,
"FailureEntity": {},
"SuccessEntity": []
}
}
现在,出于单元测试的目的,我需要对其进行反序列化,但是下面的代码将返回一个空值的对象.我要去哪里错了?
Now, for unit testing purposes, I need to deserialize it, but the code below is returning an object with empty values. Where am I going wrong?
var deserialized = JsonConvert.DeserializeObject<SplunkDataModel>(contents);
将SplunkDataModel
序列化为JSON时,将其包装在具有summary
属性的对象中.因此,当将JSON反序列化回对象时,需要使用相同的结构.有几种方法可以解决此问题.他们都达到了相同的结果.
When you serialized your SplunkDataModel
to JSON, you wrapped it in an object with a summary
property. Hence, when you deserialize the JSON back to objects, you need to use the same structure. There are several ways to go about it; they all achieve the same result.
-
声明一个类以表示JSON的根级别并反序列化为该类:
Declare a class to represent the root level of the JSON and deserialize into that:
public class RootObject
{
public SplunkDataModel Summary { get; set; }
}
然后:
var deserialized = JsonConvert.DeserializeObject<RootObject>(contents).Summary;
或者,通过示例反序列化为匿名类型的实例,然后从结果中检索对象:
Or, deserialize by example to an instance of an anonymous type, then retrieve your object from the result:
var anonExample = new { summary = new SplunkDataModel() };
var deserialized = JsonConvert.DeserializeAnonymousType(contents, anonExample).summary;
或者,反序列化为JObject,然后从中实现您的对象:
Or, deserialize to a JObject, then materialize your object from that:
JObject obj = JObject.Parse(contents);
var deserialized = obj["summary"].ToObject<SplunkDataModel>();