我想从C#Console应用程序中的Web服务调用反序列化JSON响应.JSON看起来像
{
"il_response": {
"custom_forms": [
{
"id": 84,
"name": "Request",
"note": "Notes",
"fields": [
{
"label": "Prj",
"value": [
"ABC",
"DEF"
],
"name": "Projects"
},
{
"label": "Submit Date",
"value": "October 16, 2017 ",
"name": "Submit Date"
},
{
"label": "Name",
"value": "Dhana",
"name": "Name"
}
]
}
],
"il_metadata": {}
}
}
我将所有POCO都放在名为iDTO.cs的单独类文件中
public class iResponse
{
public iResponse(){ }
public List<iDTO> data { get; set; }
}
public class iDTO
{
public iDTO() { }
}
public class Field
{
public string label { get; set; }
public object value { get; set; }
public string name { get; set; }
}
public class C_Form
{
public int id { get; set; }
public string name { get; set; }
public string note { get; set; }
public List<Field> fields { get; set; }
}
public class IlMetadata
{
}
public class IlResponse
{
public List<C_Form> c_forms { get; set; }
public IlMetadata il_metadata { get; set; }
}
public class RootObject
{
public IlResponse il_response { get; set; }
}
以下是我调用服务的代码
public class APICall
{
string BaseUR = ConfigurationManager.AppSettings["BaseURL"];
string accessToken = ConfigurationManager.AppSettings["AccessToken"];
public async Task<IHttpActionResult> Get()
{
using (var client = new HttpClient())
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
Uri uri = new Uri(BaseURL);
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await client.GetAsync(uri);
var datafile = await response.Content.ReadAsStringAsync();
var returnDataObj = JsonConvert.DeserializeObject<iLabDTO.RootObject>(datafile);
}
}
}
这里我不知道如何从JSON中的字段中获取每个名称和值属性。我看到我们可以使用每个字段,但不确定如何同时获取值和名称
答案 0 :(得分:2)
c_forms
对象上的IlResponse
属性需要与JSON对象上的相应属性具有相同的名称:
{
"il_response": {
"custom_forms": [
从上面的代码段中,您应该将c_forms
属性重命名为custom_forms
。
这是我看到的那个问题的唯一出现,但您需要确保所有C#属性名称与正在接收的JSON对象名称匹配。然后,它将为您提供C#模型对象中的属性名称,以及将在运行时保存在命名属性内的值。
答案 1 :(得分:2)
在修改Luke提到的问题之后,这使用了你的json。但是,我正在使用dta <- structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L),
name = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L),
.Label = c("A", "B"), class = "factor"),
year = c(16L, 15L, 14L, 16L, 15L, 14L, 16L, 15L, 14L),
value = c(500L, 400L, 430L, 200L, 180L, 170L, 620L, 510L, 200L)),
.Names = c("id", "name", "year", "value"),
class = "data.frame", row.names = c(NA, -9L))
dta$name_id <- with(dta, paste0(id, name))
dta
#> id name year value name_id
#> 1 1 A 16 500 1A
#> 2 1 A 15 400 1A
#> 3 1 A 14 430 1A
#> 4 2 B 16 200 2B
#> 5 2 B 15 180 2B
#> 6 2 B 14 170 2B
#> 7 3 A 16 620 3A
#> 8 3 A 15 510 3A
#> 9 3 A 14 200 3A
,而您的api则说iDTO.RootObject
。
iLabDTO.RootObject