【发布时间】:2021-01-22 15:02:24
【问题描述】:
我尝试获取一些嵌套在 JSON 中的数据,extendedData.e_ETP["value"],我通过向 API 发出请求来创建一个列表,其中包含一个键 LUS_BU,其值为 extendedData.e_ETP["value"]。
但是当我尝试访问该值时,我得到了错误:Cannot access child value on Newtonsoft.Json.Linq.JValue.
当我在 uri 中指定 `extendedData.e_ETP 不为 null 的项目的 id 时,它可以工作。
问题是,如果 LUS_BU 为 null,我想为其设置一个默认值,或者如果有,则使用 extendedData.e_ETP 中的一个
这是c#代码的一部分:
myUri = new Uri("https://ilucca.net/api/v3/users?dtContractStart=since,1900-01-01&dtContractEnd=until,2100-01-01,null&fields=id,firstName,lastName,employeeNumber,personalAccount,userAxisValues,legalEntityID,mail,dtContractEnd,dtContractStart,manager[name],birthDate,seniorityDate,gender,extendedData.e_ETP,extendedData.e_contracttype");
request = (HttpWebRequest)WebRequest.Create(myUri);
request.Headers["Authorization"] = "ApiKey";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
s = reader.ReadToEnd();
reader.Close();
response.Close();
rep = JObject.Parse(s);
salaries = rep["data"]["items"].Where(c => (string)c["name"] != "lad" && (int?)c["legalEntityID"] != 10).Select(c => new T_E_LuccaSalarie_LUS()
{
LUS_ETP = (c["extendedData"]["e_ETP"] != null ) ? (string)c["extendedData"]["e_ETP"]["value"] : "1"
}).ToList();
}
catch (WebException ex)
{
string exMessage = ex.Message;
if (ex.Response != null)
{
using (StreamReader responseReader = new StreamReader(ex.Response.GetResponseStream()))
{
exMessage = responseReader.ReadToEnd();
Console.WriteLine(exMessage);
}
}
}
JSON:
{
"header": {
"generated": "2021-01-22T16:12:53.4193558",
"serverTime": 1395,
"queryTime": 169,
"queryCount": 18,
"principal": "API Integration",
"processId": 6956
},
"data": {
"items": [
{
"id": 6,
"firstName": "John",
"lastName": "Doe",
"employeeNumber": "2",
"personalAccount": "Z0",
"userAxisValues_1": {
"id": 10,
"name": "FT04 SALES",
"url": "https://ilucca.net/api/v3/axissections/48"
},
"legalEntityID": 1,
"mail": "random@mail.com",
"dtContractEnd": "2020-01-30T00:00:00",
"dtContractStart": "2000-06-18T00:00:00",
"manager": {
"name": "John Doe"
},
"birthDate": "1959-08-23T00:00:00",
"seniorityDate": "2010-06-18T00:00:00",
"gender": "Female",
"extendedData": {
"e_ETP": null,
"e_contracttype": {
"id": 9556,
"value": 16
}
}
}
]
},
"metadata": null
}
如果您需要任何具体细节或对具体问题的说明,请随时询问。
【问题讨论】:
-
这不是有效的 JSON。您在包含对象之外有一个属性 (
"data"),并且您有一个对象嵌套在不属于某个属性的对象中(请参阅"items"数组中的第一项)。 -
正如@John 所述,您的 Json 无效。检查此屏幕截图,我已使用 app.quicktype.io 修复了您的 Json --- i.stack.imgur.com/QjgTB.png。您发布的 Json 存在大括号和逗号问题。
-
我已经相应地编辑了 JSON 部分,在尝试匿名信息时我犯了错误。谢谢
-
我在尝试复制您的场景时没有发现任何问题。检查这个小提琴 - dotnetfiddle.net/MdRp6p 它适用于
string类型转换和ToObject<string>()函数。 -
首先,感谢您的检查,我再次编辑了 JSON,当
extendedData.e_ETP为 null 时,我得到了错误。