将json值反序列化为列表

时间:2017-01-10 23:19:29

标签: c# arrays json parsing json.net

我现在经历过多个关于同样事情的问题,仍然无法理解牛顿软件是如何完全运作的。

网页的回复是,

{"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.

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

根据你的json,你需要一个根对象

public class Root
{
    public List<Status> Status {get;set;}
}
var root = JsonConvert.DeserializeObject<Root>(src);

答案 1 :(得分: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"];

答案 2 :(得分:0)

要对JSON进行解除分类,您需要像这样的类结构

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; }
}

现在,如果您仔细查看[JsonProperty("domain")] public string name { get; set; }我使用的是名称而不是域名。但由于JsonProperty,仍然会进行解除分类。

只需将其轻松反序列化即可。

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