【问题标题】:Cannot access child node value JSON无法访问子节点值 JSON
【发布时间】: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 时,我得到了错误。

标签: c# json object nested uri


【解决方案1】:

正如评论中所讨论的,如果 e_ETP 为空,那么它在您的 Json 中以 "e_ETP": null 的形式出现。该场景表示令牌是 JValue 类型,值为 null。在积极的情况下,e_ETP 类型为JObject

使用下面的代码,您可以验证类型并分配 LUS_ETP 的值

LUS_ETP = jObj["data"]["items"][0]["extendedData"]["e_ETP"].GetType() == typeof(JObject) 
               ? jObj["data"]["items"][0]["extendedData"]["e_ETP"]["value"].Value<string>() 
               : "1";

【讨论】:

  • 完美运行,非常感谢您的耐心和解释。
猜你喜欢
  • 2017-01-31
  • 1970-01-01
  • 2017-08-12
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 2020-11-15
  • 1970-01-01
相关资源
最近更新 更多