将 JSON 值反序列化为列表



好吧,我现在已经经历了关于同一件事的多个问题,仍然无法完全理解Newtonsoft的工作原理。

来自网页的响应是,

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

和反序列化对象

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

但它仍然不想执行反序列化对象,它不断返回错误,

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.

有什么想法吗?

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

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

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

为了去存储 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);

已经有答案如何将这个 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"];

相关内容

  • 没有找到相关文章

最新更新