Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 需要帮助反序列化从API返回的JSON对象吗_C#_.net_Json.net - Fatal编程技术网

C# 需要帮助反序列化从API返回的JSON对象吗

C# 需要帮助反序列化从API返回的JSON对象吗,c#,.net,json.net,C#,.net,Json.net,我有以下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.GenericEntity

我有以下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#对象,并将其发布到另一个API,该API接受完全不同的JSON格式

这是我目前的代码:

 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对象,我无法将其映射到我的类的属性:

--更新

我已经更新了我的代码,并且我能够以我想要的格式获得Jarray,但是当我尝试将jObject枚举到我的类Customer列表中时,我尝试强制转换的属性返回空值

谢谢你的回复。通过使用下面的代码,我能够得到我想要的输出。但是,如果试图将输出放入具有指定属性的Customer类列表中,则Customer类的属性将为空

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; }

    }
JObject result=JObject.Parse(wait response.Content.ReadAsStringAsync());
JArray a=(JArray)结果[“项”][“$values”];
列表项=((JArray)a)。选择(x=>新客户
{
ResultRow=(字符串)x[“ResultRow”],
工作电话=(字符串)x[“工作电话”],
电子邮件=(字符串)x[“电子邮件”],
全名=(字符串)x[“全名”],
iMISId=(字符串)x[“iMISId”],
PreferredPhone=(字符串)x[“首选电话”],
组织=(字符串)x[“组织”]
}).ToList();
公共类客户
{
[JsonProperty(“ResultRow”)]
公共字符串ResultRow{get;set;}
[JsonProperty(“工作电话”)]
公共字符串工作电话{get;set;}
[JsonProperty(“电子邮件”)]
公共字符串电子邮件{get;set;}
[JsonProperty(“全名”)]
公共字符串全名{get;set;}
[JsonProperty(“iMISId”)]
公共字符串iMISId{get;set;}
[JsonProperty(“首选电话”)]
公共字符串PreferredPhone{get;set;}
[JsonProperty(“组织”)]
公共字符串组织{get;set;}
}

您提供的代码中有错误。您试图将
属性
强制转换为
JArray
对象

如果确实希望数组位于
属性
对象中,请执行以下操作:

JArray arr = (JArray)result["Items"]["$values"][0]["Properties"]["$values"];
否则,如果要查找
属性
对象,则应改为:

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));
}

“它没有拾取我的整个JSON对象”是什么意思?顺便说一句,不要处理HttpClient。解析与反序列化不同。我编辑了我的原始注释,并添加了我对代码所做的更改以及我遇到的问题now@Junior我已经编辑了我的答案,以包括从JArray中反序列化客户。如果它确实回答了您的问题,请将其标记为一个答案,以便它可以帮助其他人。谢谢,这是可行的,但它只构建了一个客户。我想使用:JArray a=(JArray)result[“Items”][“$values”]对整个响应进行反序列化,这将返回许多客户记录。我想把它存到c#collection中。我原以为JArray函数可以做到这一点,但事实并非如此。非常感谢。这正是我要找的。foreach循环的语法非常完美!再次感谢
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"];
}