2017-01-10 95 views
0

嗯,我经历过多次的问题,现在同样的事情,还是斜面了解Newtonsoft是如何工作的完全。反序列化JSON值到列表

从网页的响应是,

{"status":[{"domain":"test.com","zone":"com","status":"active","summary":"active"}]} 

我已在类解析制成,

public class Status 
{ 
    public string name { get; set; } 
    public string zone { get; set; } 
    public string status { get; set; } 
    public string summary { get; set; } 
} 

而且DeserializeObject

IList<Status> domains = new List<Status>(); 
domains = JsonConvert.DeserializeObject<List<Status>>(src); 

,但它仍然不要执行的DeserializeObject,它使返回错误,

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code 
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Domain_Checker.Status]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. 
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. 

任何想法吗?

+0

嘿@Ale看看我提供的解决方案是否帮助了您。请确认您是否仍然面临任何问题。 :) –

回答

1

根据您的JSON,你需要一个根对象

public class Root 
{ 
    public List<Status> Status {get;set;} 
} 

var root = JsonConvert.DeserializeObject<Root>(src); 
+1

此外,重命名''通过domain' name' – Kalten

0

已经有回答如何将这个JSON解析到自己的对象。如果你不需要,你可以将json转换为JObject。从JObject你可以检索你想要这样的任意值:

var json = {"status":[{"domain":"test.com","zone":"com","status":"active","summary":"active"}]}; 

var jsonObject = JObject.Parse(json); 
var jsonProperty = jsonObject["status"][0]["domain"]; 
0

对于在[JsonProperty("domain")] public string name { get; set; } deseralizing您需要的类结构像这样

public class Status 
{ 
    [JsonProperty("domain")] 
    public string name { get; set; } 
    [JsonProperty("zone")] 
    public string zone { get; set; } 
    [JsonProperty("status")] 
    public string status { get; set; } 
    [JsonProperty("summary")] 
    public string summary { get; set; } 
} 

public class ClsStatus 
{ 
    [JsonProperty("status")] 
    public List<Status> status { get; set; } 
} 

的JSON现在,如果你仔细看看我已经使用了名称而不是域名。但仍deseralization会因为JsonProperty来完成。

只是反序列化舒服就好。

string jsonstr = File.ReadAllText("YourJSONFile"); 
ClsStatus csObj = JsonConvert.DeserializeObject<ClsStatus>(JsonStr);