簡體   English   中英

需要幫助反序列化從API返回的JSON對象

[英]Need help deserializing JSON Object returned from API

我有以下JSON輸出:

{{
  "$type": "Asi.Soa.Core.DataContracts.PagedResult`1[[Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts]], Asi.Contracts",
  "Items": {
    "$type": "System.Collections.Generic.List`1[[Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts]], mscorlib",
    "$values": [
      {
        "$type": "Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts",
        "EntityTypeName": "14",
        "Properties": {
          "$type": "Asi.Soa.Core.DataContracts.GenericPropertyDataCollection, Asi.Contracts",
          "$values": [
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "ResultRow",
              "Value": "1"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Work Phone",
              "Value": "(782) 438-7600"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Email",
              "Value": "agsaz@rmax.net"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Full Name",
              "Value": "Agazny"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "iMISId",
              "Value": "eg1"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Preferred Phone",
              "Value": "780"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Organization",
              "Value": "Re"
            }
          ]
        }
      },
      {
        "$type": "Asi.Soa.Core.DataContracts.GenericEntityData, Asi.Contracts",
        "EntityTypeName": "14",
        "Properties": {
          "$type": "Asi.Soa.Core.DataContracts.GenericPropertyDataCollection, Asi.Contracts",
          "$values": [
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "ResultRow",
              "Value": "2"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Work Phone",
              "Value": "7802"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Email",
              "Value": "aksm"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Full Name",
              "Value": "Aji"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "iMISId",
              "Value": "esa"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Preferred Phone",
              "Value": "780"
            },
            {
              "$type": "Asi.Soa.Core.DataContracts.GenericPropertyData, Asi.Contracts",
              "Name": "Organization",
              "Value": "Hom"
            }
          ]
        }
      }

我正在嘗試將此響應反序列化為可行的c#對象,並將其發布到接受完全不同的JSON格式的其他API。

到目前為止,這是我的代碼:

 using (var client = new HttpClient())
 {
      // Format headers
      client.DefaultRequestHeaders.Accept.Clear();

      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

      // Request token, and append to headers
      await AddTokenToHeaders(client);

      // Query HTTP Service                
      var response = await client.GetAsync(baseUrl + "api/IQA?querydocumentversionkey=f2005a6e-7f47-47c3-a7e7-bbd2a7b6ab38");

      if (response.IsSuccessStatusCode)
      {
           var customer = await response.Content.ReadAsStringAsync();
           JObject result = JObject.Parse(await response.Content.ReadAsStringAsync());

           JArray a = (JArray)result["Items"]["$values"][0]["Properties"];
           var test =  a.AsJEnumerable();

但是,它沒有拾取我的整個JSON對象,因此無法將其映射到我的類的屬性:

--update。

我已經更新了代碼,並且能夠以所需的格式獲取Jarray,但是當我嘗試通過jObject枚舉到類客戶列表中時,嘗試轉換的屬性將返回null。

感謝您的回復。 通過使用以下代碼,我可以獲得所需的輸出。 但是,嘗試將輸出放入具有指定屬性的“客戶列表”類中,但是我在“客戶”類的屬性上得到了空值。

JObject result = JObject.Parse(await response.Content.ReadAsStringAsync());
                JArray a = (JArray)result["Items"]["$values"];
                List<Customer> items = ((JArray)a).Select(x => new Customer
                {
                    ResultRow = (string)x["ResultRow"],
                    WorkPhone = (string)x["Work Phone"],
                    Email = (string)x["Email"],
                    FullName = (string)x["Full Name"],
                    iMISId = (string)x["iMISId"],
                    PreferredPhone = (string)x["Preferred Phone"],
                    Organization = (string)x["Organization"]
                }).ToList();


 public class Customer
    {
        [JsonProperty("ResultRow")]
        public string ResultRow { get; set; }

        [JsonProperty("Work Phone")]
        public string WorkPhone { get; set; }

        [JsonProperty("Email")]
        public string Email { get; set; }

        [JsonProperty("Full Name")]
        public string FullName { get; set; }

        [JsonProperty("iMISId")]
        public string iMISId { get; set; }

        [JsonProperty("Preferred Phone")]
        public string PreferredPhone { get; set; }

        [JsonProperty("Organization")]
        public string Organization { get; set; }

    }

您提供的代碼有誤。 您正在嘗試將Properties轉換為JArray作為對象時。

如果確實要在Properties對象中使用數組,請執行以下操作:

JArray arr = (JArray)result["Items"]["$values"][0]["Properties"]["$values"];

否則,如果您正在尋找“ Properties對象,則應該這樣做:

JObject obj = (JObject)result["Items"]["$values"][0]["Properties"];

最后,要重建Customer實例列表,可以將以下邏輯與靜態方法結合使用:

var customersJson = (JArray)result["Items"]["$values"];

var customers = new List<Customer>();

foreach (JObject o in customersJson)
{
     var customerJson = (JArray) o["Properties"]["$values"];
     customers.Add(BuildCustomer(customerJson));
}

[...]

private static Customer BuildCustomer(JArray a)
{
    return new Customer
    {
        ResultRow = GetValue(a, "ResultRow"),
        WorkPhone = GetValue(a, "Work Phone"),
        Email = GetValue(a, "Email"),
        FullName = GetValue(a, "Full Name"),
        iMISId = GetValue(a, "iMISId"),
        PreferredPhone = GetValue(a, "Preferred Phone"),
        Organization = GetValue(a, "Organization")
     };
}

private static string GetValue(JArray array, string name)
{
    JToken obj = array.FirstOrDefault(x => (string) x["Name"] == name);

    if (obj == null)
        return string.Empty;

    return (string) obj["Value"];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM