Вызов API-интерфейса SalesForce из .NET Core Web API и десериализация ответа в объекте c #? - PullRequest
0 голосов
/ 06 июля 2018

Я новичок в отделе продаж. из моего .Net Core Web API я пытаюсь вызвать мой отдел продаж.

Используя код ниже:

 string new_Contact_url = "some URL";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new_Contact_url);
                request.Method = "GET";
                request.Headers.Add("Authorization", "Bearer 00D0E00000019dU!AQUAQK7Mcfutr7Y03dsuuKy9wyMt.GzRCUve6Rll8tDr2APzuHE.J2UjXXYt1vNPiQB5Fn2BCvoC7PwEwN9OLuyTbvTAp8Dj");
                request.ContentType = "application/json; charset=utf-8";
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                WebResponse response = request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                var resp = reader.ReadToEnd();
                var obj = JsonConvert.DeserializeObject(resp);
                //inplace of object I want to convert this into List<AccountDetail>
                //List<AccountDetail>

с помощью команды Curl в командной строке я получаю этот ответ как json

{
  "eTag" : "355105a",
  "info" : {
    "cloneable" : true,
    "createable" : true,
    "deletable" : true,
    "displayColumns" : [ {
      "fieldApiName" : "Name",
      "label" : "Account Name",
      "sortable" : true
    }, {
      "fieldApiName" : "Parent.Name",
      "label" : "Parent Account",
      "sortable" : true
    }, {
      "fieldApiName" : "Type",
      "label" : "Type",
      "sortable" : true
    }, {
      "fieldApiName" : "Owner.FirstName",
      "label" : "Owner First Name",
      "sortable" : true
    }, {
      "fieldApiName" : "Owner.LastName",
      "label" : "Owner Last Name",
      "sortable" : true
    } ],
    "eTag" : "7e8d2",
    "filterLogicString" : null,
    "filteredByInfo" : [ {
      "fieldApiName" : "CreatedDate",
      "label" : "Created Date",
      "operandLabels" : [ "6-6-2018" ],
      "operator" : "GreaterThan"
    } ],
    "label" : "All Accounts",
    "listReference" : {
      "id" : "00B0N000004w1WaUAI",
      "listViewApiName" : "AllAccounts",
      "objectApiName" : "Account",
      "type" : "listView"
    },
    "orderedByInfo" : [ {
      "fieldApiName" : "Name",
      "isAscending" : true,
      "label" : "Account Name"
    } ],
    "updateable" : true,
    "userPreferences" : {
      "columnWidths" : {
        "Type" : -1,
        "Parent.Name" : -1,
        "Owner.FirstName" : -1,
        "Owner.LastName" : -1,
        "Name" : -1
      },
      "columnWrap" : {
        "Type" : false,
        "Parent.Name" : false,
        "Owner.FirstName" : false,
        "Owner.LastName" : false,
        "Name" : false
      }
    },
    "visibility" : "Public",
    "visibilityEditable" : true
  },
  "records" : {
    "count" : 2,
    "currentPageToken" : "0",
    "currentPageUrl" : "/Account/AllAccounts?pageSize=2&pageToken=0",
    "listInfoETag" : "7e6aa798",
    "nextPageToken" : "2",
    "nextPageUrl" : "/Account/AllAccounts?pageSize=2&pageToken=2",
    "previousPageToken" : null,
    "previousPageUrl" : null,
    "records" : [ {
      "apiName" : "Account",
      "childRelationships" : { },
      "eTag" : "e6aa7986b72",
      "fields" : {
        "CreatedDate" : {
          "displayValue" : null,
          "value" : "2018-06-08T10:49:31.000Z"
        },
        "Id" : {
          "displayValue" : null,
          "value" : "0010E00000M2f7aQAB"
        },
        "LastModifiedDate" : {
          "displayValue" : null,
          "value" : "2018-06-25T09:05:08.000Z"
        },
        "Name" : {
          "displayValue" : null,
          "value" : "-- UNKNOWN --"
        },
        "Owner" : {
          "displayValue" : null,
          "value" : {
            "apiName" : "User",
            "childRelationships" : { },
            "eTag" : "4686ddfd6281",
            "fields" : {
              "FirstName" : {
                "displayValue" : null,
                "value" : "System"
              },
              "Id" : {
                "displayValue" : null,
                "value" : "0050N000007jHIuQAM"
              },
              "LastName" : {
                "displayValue" : null,
                "value" : "API User"
              }
            },
            "id" : "0050N000007jHIuQAM",
            "recordTypeInfo" : null
          }
        },
        "OwnerId" : {
          "displayValue" : null,
          "value" : "0050N000007jHIuQAM"
        },
        "Parent" : {
          "displayValue" : null,
          "value" : null
        },
        "ParentId" : {
          "displayValue" : null,
          "value" : null
        },
        "SystemModstamp" : {
          "displayValue" : null,
          "value" : "2018-06-25T09:05:08.000Z"
        },
        "Type" : {
          "displayValue" : null,
          "value" : null
        }
      },
      "id" : "0010E00000M2f7aQAB",
      "recordTypeInfo" : null
    }, {
      "apiName" : "Account",
      "childRelationships" : { },
      "eTag" : "815b8ac88",
      "fields" : {
        "CreatedDate" : {
          "displayValue" : null,
          "value" : "2018-06-08T10:48:00.000Z"
        },
        "Id" : {
          "displayValue" : null,
          "value" : "0010"
        },
        "LastModifiedDate" : {
          "displayValue" : null,
          "value" : "2018-06-25T09:04:33.000Z"
        },
        "Name" : {
          "displayValue" : null,
          "value" : "AAA Transportation"
        },
        "Owner" : {
          "displayValue" : null,
          "value" : {
            "apiName" : "User",
            "childRelationships" : { },
            "eTag" : "4686ddfd62818d54f92a08bd73726606",
            "fields" : {
              "FirstName" : {
                "displayValue" : null,
                "value" : "System"
              },
              "Id" : {
                "displayValue" : null,
                "value" : "0050N000007jHIuQAM"
              },
              "LastName" : {
                "displayValue" : null,
                "value" : "API User"
              }
            },
            "id" : "0050N000007jHIuQAM",
            "recordTypeInfo" : null
          }
        },
        "OwnerId" : {
          "displayValue" : null,
          "value" : "0050N000007jHIuQAM"
        },
        "Parent" : {
          "displayValue" : null,
          "value" : null
        },
        "ParentId" : {
          "displayValue" : null,
          "value" : null
        },
        "SystemModstamp" : {
          "displayValue" : null,
          "value" : "2018-06-25T09:04:33.000Z"
        },
        "Type" : {
          "displayValue" : null,
          "value" : null
        }
      },
      "id" : "0010E000",
      "recordTypeInfo" : null
    } ]
  }
}

Из этого ответа я понял, что в нем много метаданных. Важной частью, которую я хочу получить из ответа, является тег records

Я создал класс Equivalent C # из тега записи

public class AccountDetail
    {

        public string Etag { get; set; }
        public string CreatedDate { get; set; }
        public string Id { get; set; }
        public string LastModifiedDate { get; set; }
        public string Name { get; set; }
        public string ApiName { get; set; }

        public List<OwnerDetails> Owners { get; set; }
    }

    public class OwnerDetails
    {
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string ApiName { get; set; }

    }

Итак, как мне извлечь информацию из тега records в эквивалентный список C # object.this line var obj = (Список) JsonConvert.DeserializeObject (resp);

Ответы [ 2 ]

0 голосов
/ 06 июля 2018

Вы можете использовать Newtonsoft.Json

var files = JObject.Parse(YourJSON);
var recList = files.SelectTokens("$..records..records").ToList();
foreach (JObject obj in recList.Children())
 {
   foreach (JProperty prop in obj.Children())
      {
        var key = prop.Name.ToString();
        var value = prop.Value.ToString();
         //Do your stuffs here
      }

  }
0 голосов
/ 06 июля 2018

JsonConverter может помочь вам достичь того, что вам нужно. Просто реализуйте конвертер для вашего класса со всеми необходимыми правилами заполнения свойств вашего объекта и используйте его при десериализации, например:

List<AccountDetail> accountDetails = JsonConvert.DeserializeObject<List<AccountDetail>>(json, new ListOfAccountDetailsJsonConverter(typeof(List<AccountDetail>)));
...