将JSON解析为对象

本文关键字:对象 JSON | 更新日期: 2023-09-27 18:20:01

我从服务器到c#客户端得到一个json字符串/对象。

这是JSON:

[
{"PrintId":1,"PrintRef":"00000000-0000-0000-0000-000000000000","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"},
{"PrintId":2,"PrintRef":"39a10cee-7cb3-4ed3-aec2-293761eed96d","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"}]

我正试图将其转换为一个对象列表,如下所示:

public IEnumerable<Model.Print> Get()
{
    var print = new List<Model.Print>();
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(Shared.URL);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Shared.HeaderType));
        var response = client.GetAsync(route + "?" + GeneralTags.CUSTOMER_REF + "=" + new Guid().ToString()).Result;
        if (response.IsSuccessStatusCode)
        {
            var strJson = response.Content.ReadAsStringAsync().Result;
            var strJson2 = (JObject)JsonConvert.DeserializeObject(strJson);
            List<Model.Print> items = strJson2["data"].Select(x => new Model.Print
            {
                CompanyRef = (Guid)x["CompanyRef"],
                Header = (string)x["Header"],
                PrintId = (int)x["PrintId"],
                PrintRef = (Guid)x["PrintRef"],
                TC = (string)x["TC"]
            }).ToList();                 
        }
        else
        {
            evError(new Exception(String.Format("{0}: {1}", (int)response.StatusCode, response.ReasonPhrase)), ErrorTags.PRINT_GET);
        }
    }
    return print;
}

但它在这一行出错:

var strJson2 = (JObject)JsonConvert.DeserializeObject(strJson);

这就是错误:

Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.

将JSON解析为对象

您的顶级json结构是一个数组,而不是一个对象。因此,您需要转换为JArray而不是JObject:

var root = (JObject)JsonConvert.DeserializeObject(strJson);

如果你只想提取所有对象:

var objs = ((JArray)JsonConvert.DeserializeObject(json)).Values<JObject>();