Reputation: 39
I am using Newtonsoft.Json to Deserialize json string to Object, but I can't judge if the node is null
or not. eg. jo["data"]["prevtime"]
, sometimes json
has the node of ["prevtime"]
, sometimes doesn't have ["prevtime"]
. If ["prevtime"]
is null
, it will report an error.
var jo = JObject.Parse(content);
if (jo["data"].ToString() == "")
return new StatusCollection();
var jInfo = jo["data"]["info"];
StatusCollection list = new StatusCollection();
Status status = null;
if (jInfo != null)
{
foreach (var j in jInfo.Children())
{
if (jo["data"]["prevtime"] != null)
{
status.Nexttime = jo["data"]["nexttime"].ToString();
status.Prevtime = jo["data"]["prevtime"].ToString();
}
status = j.ToObject<Status>();
if (!string.IsNullOrEmpty(status.Head))
{
status.Head += "/50";
}
if (!string.IsNullOrEmpty(status.From))
{
status.From = "来自" + status.From;
}
list.Add(status);
}
}
Upvotes: 2
Views: 4061
Reputation: 2688
Try to select the token you want, and there is a property to get the token value
if (jo["data"].Select("prevtime") != null)
{
status.Prevtime = jo["data"].Value<string>("prevtime");
status.Nexttime = jo["data"].Value<string>("nexttime");
}
JSON.NET Documentation:
Upvotes: 2
Reputation: 31
In the current version, it would be like :
if (jo["data"].Select***Token***("prevtime") != null)
{
status.Prevtime = jo["data"].Value<string>("prevtime");
status.Nexttime = jo["data"].Value<string>("nexttime");
}
Upvotes: 3