如何反序列化C#对象的单个属性响应



我正在测试API,目前正在测试一个返回Long数据类型Id的Post方法。我创建了一个C#对象类,其中还有其他属性,它将从另一个API调用返回。目前,这个Post调用只返回一个Id,我想将它映射到类中的Id属性,但我得到了一个异常。无法从System.Int64强制转换或转换为Model类

//这是我的型号

public class Model
{
public long id { get; set; }
public string name { get; set; }
public long type { get; set; }
}
// Here is the call I am making.. FYI I am using RestSharp
response = HttpPost("URl");
var id =  JsonConvert.DeserializeObject<Model.id>(restResponse.Content); //How can I map just the Id.

我从API的回复是一个长数据类型ex:658

long替换Model.id

JsonConvert.DeserializeObject<long>

你可以像这样设置

Model model = new Model();
model.id = JsonConvert.DeserializeObject<long>...

您可以根据您的模型调整此示例。

using (var client = new HttpClient())
{
string url = string.Format("your-api-url");
var response = client.GetAsync(url).Result;
string responseAsString = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<YourModel>(responseAsString);
}
public class YourModel
{
[JsonProperty("confirmed")]
public ValueModel Confirmed { get; set; }
[JsonProperty("recovered")]
public ValueModel Recovered { get; set; }
[JsonProperty("values")]
public ValueModel Values { get; set; }
}
public class ValueModel
{
[JsonProperty("value")]
public int Value { get; set; }
}

最新更新