【问题标题】:Get Name of Id from Json using linq使用 linq 从 Json 获取 ID 的名称
【发布时间】:2020-02-04 11:54:24
【问题描述】:

我有 JSON 如下

{
  "code": "0",
  "message": "success",
  "appointments": [
    {
      "patient_id": "1",
      "patient_name": "Jairaj Test",
    },
    {
      "patient_id": "2",
      "physician_name": "Test Physician",
    }
  ]
}

我想在 c# 中使用 LINQ 使用 Patientid 从中获取 pateint_name

我试过了

var jsonLinq = JObject.Parse(ResponseContent);
jsonLinq["appointments"].AsEnumerable().Select(p => p["patient_name"]).Where(s => Convert.ToString(s["patient_id"]).Equals(2)

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: c# .net json linq lambda


【解决方案1】:
jsonLinq["appointments"].AsEnumerable().Where(s => Convert.ToString(s["patient_id"]).Equals(2)).Select(p => p["patient_name"]).FirstOrDefault().ToString();

得到答案!!!

【讨论】:

    【解决方案2】:

    Where 开始,然后是Select

    var results =  jsonLinq["appointments"]
                    .Where(s => s["patient_id"].ToString() == "1")
                    .Select(p => p["patient_name"]);
    

    【讨论】:

      【解决方案3】:

      你可以使用

      var name = jsonLinq.SelectToken($"$.appointments[?(@.patient_id == '{idToSearch}')].patient_name")
                         .Value<string>();
      

      【讨论】:

        【解决方案4】:

        SelectWhere 的顺序在这里很重要。您需要先使用Where 过滤完整的“患者”条目,然后再使用Select 提取“患者姓名”属性。一旦您运行Select 映射函数,您的IEnumerable 将只包含您选择的内容,而不是您从中选择它的元素。

        SelectWhere 之前(不起作用):

        var jsonLinq = JObject.Parse(ResponseContent);
        // whole JObject
        jsonLinq["appointments"]
        // "appointments" object
          .AsEnumerable()
          // "appointments" as list of KeyValuePair<string, JToken>
          .Select(p => p["patient_name"])
          // list of all "patient_name" JTokens
          .Where(s => Convert.ToString(s["patient_id"]).Equals(2))
          // Error: JTokens "Jairaj Test" and "Test Physician" don't have any "patient_id" property
        

        WhereSelect 之前(有效):

        var jsonLinq = JObject.Parse(ResponseContent);
        // whole JObject
        jsonLinq["appointments"]
        // "appointments" object
          .AsEnumerable()
          // "appointments" as list of KeyValuePair<string, JToken>
          .Where(s => Convert.ToString(s["patient_id"]).Equals(2))
          // filtered list of all patient objects where "patient_id" is "2"
          .Select(p => p["patient_name"])
          // list of all "patient_names" from the previously filtered list
        

        【讨论】:

          【解决方案5】:

          如果您的 JSON 是非动态的,您还可以创建一些模型类来代表您的 JSON 数据:

          public class Appointment
          {
              [JsonProperty("patient_id")]
              public string PatientId { get; set; }
              [JsonProperty("patient_name")]
              public string PatientName { get; set; }
              [JsonProperty("physician_name")]
              public string PhysicianName { get; set; }
          }
          
          public class RootObject
          {
              [JsonProperty("code")]
              public string Code { get; set; }]
              [JsonProperty("message")]
              public string Message { get; set; }
              [JsonProperty("appointments")]
              public List<Appointment> Appointments { get; set; }
          }
          

          然后您可以使用Where()Select() 反序列化并获取患者姓名:

          var jsonObject = JsonConvert.DeserializeObject<RootObject>(response);
          
          var patient = jsonObject
              .Appointments
              .Where(a => a.PatientId.Equals("2"))
              .Select(a => a.PatientName);
          

          或者您可以简单地检索使用FirstOrDefault() 找到的第一个:

          var patient = jsonObject
             .Appointments
             .FirstOrDefault(a => a.PatientId.Equals("2"))
             .PatientName;
          

          【讨论】:

            猜你喜欢
            • 2012-02-18
            • 2021-07-09
            • 1970-01-01
            • 2014-04-04
            • 2016-07-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多