Json 反序列化为对象 C# Json.net

Json Deserialize into object C# Json.net

我正在尝试将 json 字符串反序列化为 class,但是,属性 一直为空。

IRestResponse companyResponse = companyClient.Execute(companyRequest);
Company companyList = JsonConvert.DeserializeObject<Company>(companyResponse.Content);

public class Company
{
     public string id { get; set; }
}

公司get请求拉取了其他几条数据,我只对ID值感兴趣。根据我在本网站和互联网上阅读的内容,以上内容应该有效。

编辑:返回的 get

"{\"companies\":[{\"id\":\"7f91f557-4d12-486e-ba89-09c46c8a56b7\",\"name\":\"storEDGE Demo\",\"contact_email\":\"\",\"contact_phone\":\"5555555555\",\"rental_center_subdomain\":null,\"websites\":[{\"provider\":\"storedge\",\"provider_id\":\"storedgedemo\"}],\"eligible_for_voyager_website\":[{\"provider_exists\":true,\"api_association_exists\":true}],\"sales_demo\":true,\"pusher_channel\":\"private-company-7f91f5574d12486eba8909c46c8a56b7\",\"address\":{\"id\":\"b4afccb5-4d5d-4ccd-9965-67280cb868c5\",\"address1\":\"1234 storEDGE St. \",\"address2\":\"\",\"city\":\"Kansas City\",\"state\":\"MO\",\"postal\":\"66205\",\"country\":\"US\",\"full_address\":\"1234 storEDGE St. , Kansas City, MO 66205\",\"latitude\":null,\"longitude\":null,\"time_zone_id\":\"America/Chicago\",\"time_zone_offset\":\"-05:00\",\"invalid_data\":false,\"label\":\"Home\"}},{\"id\":\"249f62c7-64fb-4e12-ac91-9a4a30c1ab1c\",\"name\":\"SafeStor Insurance Company\",\"contact_email\":\"ponderosainsurance@gmail.com\",\"contact_phone\":\"\",\"rental_center_subdomain\":null,\"websites\":[],\"eligible_for_voyager_website\":[{\"provider_exists\":false,\"api_association_exists\":false}],\"sales_demo\":false,\"pusher_channel\":\"private-company-249f62c764fb4e12ac919a4a30c1ab1c\",\"address\":{\"id\":\"aa5a7775-1eb9-4fc6-8b91-b2179b9fd1fb\",\"address1\":\"5901 Catalina\",\"address2\":\"\",\"city\":\"Fairway\",\"state\":\"KS\",\"postal\":\"66205\",\"country\":\"US\",\"full_address\":\"5901 Catalina, Fairway, KS 66205\",\"latitude\":null,\"longitude\":null,\"time_zone_id\":\"America/Chicago\",\"time_zone_offset\":\"-05:00\",\"invalid_data\":false,\"label\":\"Home\"}}],\"meta\":{\"pagination\":{\"current_page\":1,\"total_pages\":1,\"per_page\":100,\"total_entries\":2,\"previous_page\":null,\"next_page\":null},

你的反序列化期望 json 对象的内容 属性 id 这显然不是传递的内容。

根据您发布的文件内容,您应该添加另一个class并更改反序列化类型。

public class Response
{
    [JsonProperty("companies")
    public Company[] Companies { get; set; }
}

var companiesResponse = JsonConvert.DeserializeObject<Response>(companyResponse.Content);

您将 JSON 反序列化为错误的类型。

显示的 JSON 是一个带有数组 属性 的 JSON 对象,我认为它是公司的集合。

使用以下模型

public class RootObject {
    public Company[] companies { get; set; }
}

从那里你可以

var json = companyResponse.Content;
var result = JsonConvert.DeserializeObject<RootObject>(json);
Company[] companies = result.companies;