将JSON解析为对象

时间:2015-11-01 14:20:30

标签: c# json raspberry-pi jsonobject

我从服务器获取一个json字符串/对象到我的c#client。

这是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'.

1 个答案:

答案 0 :(得分:2)

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

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

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

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