I am calling a third-party API with HttpClient GET Request and it works fine. The response is quite complex of objects. All I want to do is to extract a specific attribute within these objects. Here is the response Json
"creationTime": "2021-11-06T12:22:49.602Z",
"currency": "USD",
"customer": {
"firstName": "xxxx"
},
"id": "xxxx",
"lastUpdatedTime": "2021-11-06T12:22:51.689Z",
"merchant": "xxx",
"merchantAmount": 33,
"merchantCategoryCode": "5311",
"merchantCurrency": "USD",
"reference": "XX",
"result": "SUCCESS",
"sourceOfFunds": {
"provided": {
"card": {
"brand": "MASTERCARD",
"expiry": {
"month": "X",
"year": "XX"
},
"fundingMethod": "DEBIT",
"nameOnCard": "XXX",
"number": "XXXXX123",
"scheme": "MASTERCARD",
"storedOnFile": "NOT_STORED"
}
},
"type": "CARD"
},
"status": "CAPTURED",
"totalAuthorizedAmount": 33,
"totalCapturedAmount": 33,
"totalRefundedAmount": 0,
"transaction": [
{
"3DSecure": {
"acsEci": "02",
"authenticationToken": "XXXX+XXXX=",
"paResStatus": "Y",
"veResEnrolled": "Y",
"xid": "mmmXXX"
},
"3DSecureId": "XXX",
"authorizationResponse": {
"cardSecurityCodeError": "M",
"commercialCardIndicator": "1",
"date": "1106",
"financialNetworkCode": "XX",
"financialNetworkDate": "2021-11-06",
"posData": "XXX",
"posEntryMode": "xxx",
"processingCode": "000000",
"responseCode": "00",
"stan": "22443",
"time": "122249",
"transactionIdentifier": "014VPH"
},
"customer": {
"firstName": "XXXX"
},
"device": {
},
"gatewayEntryPoint": "CHECKOUT",
"merchant": "XXXX",
"order": {
"amount": 33,
"chargeback": {
"amount": 0,
"currency": "USD"
},
"creationTime": "2021-11-06T12:22:49.602Z",
"currency": "USD",
"description": "243",
"id": "xxxxx",
"lastUpdatedTime": "2021-11-06T12:22:51.689Z",
"merchantAmount": 33,
"merchantCategoryCode": "xxx",
"merchantCurrency": "IQD",
"reference": "243",
"status": "CAPTURED",
"totalAuthorizedAmount": 33,
"totalCapturedAmount": 33,
"totalRefundedAmount": 0
},
"response": {
"acquirerCode": "00",
"acquirerMessage": "Approved",
"cardSecurityCode": {
"acquirerCode": "M",
"gatewayCode": "MATCH"
},
"gatewayCode": "APPROVED"
},
"result": "SUCCESS",
"sourceOfFunds": {
"provided": {
"card": {
"brand": "MASTERCARD",
"expiry": {
"month": "x",
"year": "xx"
},
"fundingMethod": "DEBIT",
"nameOnCard": "xxxxx",
"number": "xxxxxx",
"scheme": "MASTERCARD",
"storedOnFile": "NOT_STORED"
}
},
"type": "CARD"
},
"timeOfLastUpdate": "2021-11-06T12:22:51.689Z",
"timeOfRecord": "2021-11-06T12:22:49.617Z",
}
]
}
I'd like to extract "status": "CAPTURED" and "acquirerCode": "00" . here is what I tried
var client = new HttpClient();
string _ContentType = "application/json";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);
var _UserAgent = "d-fens HttpClient";
client.DefaultRequestHeaders.Add("User-Agent", _UserAgent);
HttpResponseMessage response;
response = await client.GetAsync(api_URL);
var resContent = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
var content = response.Content.ReadAsStringAsync().Result;
return Ok(resContent);
Extracting these values would solve the issue I'm facing. Thanks in advance
if you need just this 2 values the easiest way is
var json = response.Content.ReadAsStringAsync().Result;
var result = JObject.Parse(json);
var status= result["status"];
var acquirerCode= result["transaction"][0]["response"]["acquirerCode"];
output
CAPTURED
00
And there is a hard way
var json = response.Content.ReadAsStringAsync().Result;
var jsonDeserialized=JsonConvert.DeserializeObject<Data>(json);
var status= jsonDeserialized.Status;
var acquirerCode=jsonDeserialized.Transaction.Select(t => t.Response.AcquirerCode).FirstOrDefault();
classes
public partial class Data
{
[JsonProperty("creationTime")]
public DateTimeOffset CreationTime { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("customer")]
public Customer Customer { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("lastUpdatedTime")]
public DateTimeOffset LastUpdatedTime { get; set; }
[JsonProperty("merchant")]
public string Merchant { get; set; }
[JsonProperty("merchantAmount")]
public long MerchantAmount { get; set; }
[JsonProperty("merchantCategoryCode")]
public long MerchantCategoryCode { get; set; }
[JsonProperty("merchantCurrency")]
public string MerchantCurrency { get; set; }
[JsonProperty("reference")]
public string Reference { get; set; }
[JsonProperty("result")]
public string Result { get; set; }
[JsonProperty("sourceOfFunds")]
public SourceOfFunds SourceOfFunds { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("totalAuthorizedAmount")]
public long TotalAuthorizedAmount { get; set; }
[JsonProperty("totalCapturedAmount")]
public long TotalCapturedAmount { get; set; }
[JsonProperty("totalRefundedAmount")]
public long TotalRefundedAmount { get; set; }
[JsonProperty("transaction")]
public Transaction[] Transaction { get; set; }
}
public partial class Customer
{
[JsonProperty("firstName")]
public string FirstName { get; set; }
}
public partial class SourceOfFunds
{
[JsonProperty("provided")]
public Provided Provided { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
public partial class Provided
{
[JsonProperty("card")]
public Card Card { get; set; }
}
public partial class Card
{
[JsonProperty("brand")]
public string Brand { get; set; }
[JsonProperty("expiry")]
public Expiry Expiry { get; set; }
[JsonProperty("fundingMethod")]
public string FundingMethod { get; set; }
[JsonProperty("nameOnCard")]
public string NameOnCard { get; set; }
[JsonProperty("number")]
public string Number { get; set; }
[JsonProperty("scheme")]
public string Scheme { get; set; }
[JsonProperty("storedOnFile")]
public string StoredOnFile { get; set; }
}
public partial class Expiry
{
[JsonProperty("month")]
public string Month { get; set; }
[JsonProperty("year")]
public string Year { get; set; }
}
public partial class Transaction
{
[JsonProperty("3DSecure")]
public The3DSecure The3DSecure { get; set; }
[JsonProperty("3DSecureId")]
public string The3DSecureId { get; set; }
[JsonProperty("authorizationResponse")]
public AuthorizationResponse AuthorizationResponse { get; set; }
[JsonProperty("customer")]
public Customer Customer { get; set; }
[JsonProperty("device")]
public Device Device { get; set; }
[JsonProperty("gatewayEntryPoint")]
public string GatewayEntryPoint { get; set; }
[JsonProperty("merchant")]
public string Merchant { get; set; }
[JsonProperty("order")]
public Order Order { get; set; }
[JsonProperty("response")]
public Response Response { get; set; }
[JsonProperty("result")]
public string Result { get; set; }
[JsonProperty("sourceOfFunds")]
public SourceOfFunds SourceOfFunds { get; set; }
[JsonProperty("timeOfLastUpdate")]
public DateTimeOffset TimeOfLastUpdate { get; set; }
[JsonProperty("timeOfRecord")]
public DateTimeOffset TimeOfRecord { get; set; }
}
public partial class AuthorizationResponse
{
[JsonProperty("cardSecurityCodeError")]
public string CardSecurityCodeError { get; set; }
[JsonProperty("commercialCardIndicator")]
public long CommercialCardIndicator { get; set; }
[JsonProperty("date")]
public long Date { get; set; }
[JsonProperty("financialNetworkCode")]
public string FinancialNetworkCode { get; set; }
[JsonProperty("financialNetworkDate")]
public DateTimeOffset FinancialNetworkDate { get; set; }
[JsonProperty("posData")]
public string PosData { get; set; }
[JsonProperty("posEntryMode")]
public string PosEntryMode { get; set; }
[JsonProperty("processingCode")]
public string ProcessingCode { get; set; }
[JsonProperty("responseCode")]
public string ResponseCode { get; set; }
[JsonProperty("stan")]
public long Stan { get; set; }
[JsonProperty("time")]
public long Time { get; set; }
[JsonProperty("transactionIdentifier")]
public string TransactionIdentifier { get; set; }
}
public partial class Device
{
}
public partial class Order
{
[JsonProperty("amount")]
public long Amount { get; set; }
[JsonProperty("chargeback")]
public Chargeback Chargeback { get; set; }
[JsonProperty("creationTime")]
public DateTimeOffset CreationTime { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("description")]
public long Description { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("lastUpdatedTime")]
public DateTimeOffset LastUpdatedTime { get; set; }
[JsonProperty("merchantAmount")]
public long MerchantAmount { get; set; }
[JsonProperty("merchantCategoryCode")]
public string MerchantCategoryCode { get; set; }
[JsonProperty("merchantCurrency")]
public string MerchantCurrency { get; set; }
[JsonProperty("reference")]
public long Reference { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("totalAuthorizedAmount")]
public long TotalAuthorizedAmount { get; set; }
[JsonProperty("totalCapturedAmount")]
public long TotalCapturedAmount { get; set; }
[JsonProperty("totalRefundedAmount")]
public long TotalRefundedAmount { get; set; }
}
public partial class Chargeback
{
[JsonProperty("amount")]
public long Amount { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
}
public partial class Response
{
[JsonProperty("acquirerCode")]
public string AcquirerCode { get; set; }
[JsonProperty("acquirerMessage")]
public string AcquirerMessage { get; set; }
[JsonProperty("cardSecurityCode")]
public CardSecurityCode CardSecurityCode { get; set; }
[JsonProperty("gatewayCode")]
public string GatewayCode { get; set; }
}
public partial class CardSecurityCode
{
[JsonProperty("acquirerCode")]
public string AcquirerCode { get; set; }
[JsonProperty("gatewayCode")]
public string GatewayCode { get; set; }
}
public partial class The3DSecure
{
[JsonProperty("acsEci")]
public string AcsEci { get; set; }
[JsonProperty("authenticationToken")]
public string AuthenticationToken { get; set; }
[JsonProperty("paResStatus")]
public string PaResStatus { get; set; }
[JsonProperty("veResEnrolled")]
public string VeResEnrolled { get; set; }
[JsonProperty("xid")]
public string Xid { get; set; }
}
Related
Returned object :
{
"_expands": [],
"size": 3,
"start": 3,
"limit": 3,
"isLastPage": false,
"_links": {
"base": "http://host:port/context/rest/desk",
"context": "context",
"next": "http://host:port/context/rest/desk",
"prev": "http://host:port/context/rest/desk"
},
"values": [
{
"status": "Waiting for Customer",
"statusDate": {
"iso8601": "2015-10-08T14:05:00+0700",
"polaris": "2015-10-08T14:05:00.000+0700",
"friendly": "Today 14:05 PM",
"epochMillis": 1444287900000
}
},
{
"status": "Waiting for Support",
"statusDate": {
"iso8601": "2015-10-08T14:01:00+0700",
"polaris": "2015-10-08T14:01:00.000+0700",
"friendly": "Today 14:01 PM",
"epochMillis": 1444287660000
}
},
{
"status": "Waiting for Customer",
"statusDate": {
"iso8601": "2015-10-08T14:00:00+0700",
"polaris": "2015-10-08T14:00:00.000+0700",
"friendly": "Today 14:00 PM",
"epochMillis": 1444287600000
}
}
]
}
Classes :
public class polarisState
{
public string[] expands { get; set; }
public int size { get; set; }
public int start { get; set; }
public int limit { get; set; }
public bool isLastPage { get; set; }
public _links links { get; set; }
public values[] values { get; set; }
}
public class _links
{
//public string base {get; set;}
public string context { get; set; }
public string next { get; set; }
public string prev { get; set; }
}
public class values
{
public string status { get; set; }
public statusDate statusDate { get; set; }
}
public class statusDate
{
public string iso8601 { get; set; }
public string polaris { get; set; }
public string friendly { get; set; }
public int epochMillis { get; set; }
}
code below :
if (resp2.IsSuccessStatusCode)
{
var values = JsonConvert.DeserializeObject<JiraState>(resp2.Content.ReadAsStringAsync().Result); }
You should change the class polarisState to
public class polarisState
{
public List<string> expands { get; set; }
public int size { get; set; }
public int start { get; set; }
public int limit { get; set; }
public bool isLastPage { get; set; }
public _links links { get; set; }
public List<values> values { get; set; }
}
array to List.
Then change the statusDate to:
public class statusDate
{
public string iso8601 { get; set; }
public string polaris { get; set; }
public string friendly { get; set; }
public long epochMillis { get; set; }
}
change the epochMillis from int to long value type.
It's done.
Use the async method and change the code as follow:
var content = await resp2.Content.ReadAsStringAsync();
var values = JsonConvert.DeserializeObject<polarisState>(content);
I want to deserialize a json request but it is not working in Web API. My code is below for the deserialization. Can you please tell me what I am doing wrong?
[HttpPost]
public HttpResponseMessage AddOrder(string username , string password, JObject jsonResult)
{
try
{
AuthRepository _auth = new AuthRepository();
OrderDTO.RootObject O = new OrderDTO.RootObject();
O = JsonConvert.DeserializeObject<OrderDTO.RootObject>(jsonResult.ToString());
}
catch (Exception ex)
{
return Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, ex);
}
}
This is the JSON that will received by our method:
{
"token": "D8xJD2CI6PrkB3q5gnlT",
"shipment": {
"hawb": "0800780108",
"service_level": "CURBSIDE",
"status": "NEW",
"description": "bundle of things",
"service_level_code": "CB",
"delivery_date": "8/22/2019 5:01:00 PM",
"delivery2_date": "8/22/2019 12:00:00 AM",
"origin": {
"name": "ESTES EXPRESS BOSTON-080",
"nbr": "0800780108",
"phone": "508-513-0120",
"email": "",
"address1": "215 BODWELL ST",
"city": "AVON",
"state": "MA",
"zip_postal_code": "02322",
"country": "US"
},
"dest": {
"name": "JOSEPH VINOGRAD",
"nbr": "",
"phone": "",
"email": "",
"address1": "14 CORTLAND DR",
"city": "Sharon",
"state": "MA",
"zip_postal_code": "02067",
"country": "US"
},
"piece_count": "2",
"dangerous_goods": "0",
"weight": 190
}
}
Code for class
public class OrderDTO
{
public class Origin
{
public string name { get; set; }
public string nbr { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string address1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip_postal_code { get; set; }
public string country { get; set; }
}
public class Dest
{
public string name { get; set; }
public string nbr { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string address1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip_postal_code { get; set; }
public string country { get; set; }
}
public class Shipment
{
public string hawb { get; set; }
public string service_level { get; set; }
public string status { get; set; }
public string description { get; set; }
public string service_level_code { get; set; }
public string delivery_date { get; set; }
public string delivery2_date { get; set; }
public Origin origin { get; set; }
public Dest dest { get; set; }
public string piece_count { get; set; }
public string dangerous_goods { get; set; }
public double weight { get; set; }
}
public class RootObject
{
public string token { get; set; }
public Shipment shipment { get; set; }
}
}
You can add username and password to your OrderDTO class (or another class containing these three objects) and then change action definition like:
public HttpResponseMessage AddOrder(OrderDRO input).
Then you don't need to use json serialization and easily you can do your logic.
I'm using this code to pull a list of email addresses and search them for a specific address, if it's a duplicate then I need to pull the "id" (the value starts with "lead_") which is in the Datam class and/or Contacts
var emails = json
// Enumerate through all data
.Data
// Enumerate through all contacts of all data
.SelectMany(d => d.Contacts)
// Enumerate through all emails of all contacts
.SelectMany(c => c.Emails)
// Get email value
.Select(e => e.EmailValue)
So I have my list of emails, but how do I attach the ID's to them, I assume I need to create an anonymous type?
I've tried this but can't figure out how to go back to the root
JSON:
{
"data": [
{
"addresses": [],
"contacts": [
{
"created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"date_created": "2017-12-03T05:42:30.737000+00:00",
"date_updated": "2017-12-03T05:45:32.227000+00:00",
"emails": [
{
"email": "testemail#testemail.com",
"type": "office"
}
],
"id": "cont_kH9tcx970T3ZTGKPPP2vh5u3Ha8P9Rjz6gGqflgzwvy",
"integration_links": [
{
"name": "LinkedIn Search",
"url": "https://www.linkedin.com/search/results/index/?keywords=Test%20Woodard"
}
],
"lead_id": "lead_12Rz7R2TrWmwUhCGVTRh8rt6A8hokaXgujSEPlfoWpD",
"name": "Test User",
"organization_id": "orga_iFnIMLDbvGevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
"phones": [
{
"phone": "+15558675309",
"phone_formatted": "+1 555-867-5309",
"type": "office"
}
],
"title": "",
"updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"urls": []
}
],
"created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"created_by_name": "Test User",
"custom": {
"Date Created": "2017-12-03",
"Initial Service": "Men's Health",
"Lead Owner": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"Marketing Source": "Bing"
},
"custom.lcf_UfNWMxg2f7UU28rI9RAhTEAPWMyXU1UFZb5oNJEgR0K": "Bing",
"custom.lcf_dDtwGb41tpi8XkVMMgxdHxEJ92A7ujreRU1aPPZd95B": "Chiropractor",
"custom.lcf_fUNjcSq8bemwdQL0wogc3wgyxmz3ZD17fKdv8s4wkWV": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"custom.lcf_y37bo72LesrOBWuVPSoRfIazw5KflujnV81nGCfcjZ3": "2017-12-03",
"date_created": "2017-12-03T05:42:30.733000+00:00",
"date_updated": "2017-12-03T05:45:32.234000+00:00",
"description": "",
"display_name": "test",
"html_url": "https://app.close.io/lead/lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpG/",
"id": "lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpD",
"integration_links": [
{
"name": "Google Search",
"url": "http://google.com/search?q=test"
}
],
"name": "test",
"opportunities": [
{
"confidence": 50,
"contact_id": null,
"contact_name": null,
"created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"created_by_name": "Test User",
"date_created": "2017-12-03T05:44:31.131000+00:00",
"date_lost": null,
"date_updated": "2017-12-03T05:44:31.131000+00:00",
"date_won": null,
"id": "oppo_xQ5S1dHMjDWoeUBAigtyiwuwFUkxtbxHURQX5UaL7fT",
"integration_links": [],
"lead_id": "lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpD",
"lead_name": "test",
"note": "New Lead",
"organization_id": "orga_iFnIMLDbvNevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
"status_id": "stat_SwQmzqoIqIt20j9YBDxIYem11GyZPGL30G7PdkWYdvG",
"status_label": "Chiropractor",
"status_type": "active",
"updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"updated_by_name": "Test User",
"user_id": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"user_name": "Test User",
"value": 140000,
"value_currency": "USD",
"value_formatted": "$1,400",
"value_period": "one_time"
}
],
"organization_id": "orga_iFnIMLDbvNevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
"status_id": "stat_auhCEJZNhaUnX9DHdrCaZ5r5mhpqxjfaE1hdwnPz6xx",
"status_label": "Potential",
"tasks": [],
"updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"updated_by_name": "Test User",
"url": null
}
],
"has_more": false,
"total_results": 1
}
public partial class Welcome
{
[JsonProperty("data")]
public Datum[] Data { get; set; }
[JsonProperty("has_more")]
public bool HasMore { get; set; }
[JsonProperty("total_results")]
public long TotalResults { get; set; }
}
public partial class Datum
{
[JsonProperty("addresses")]
public object[] Addresses { get; set; }
[JsonProperty("contacts")]
public Contact[] Contacts { get; set; }
[JsonProperty("created_by")]
public string CreatedBy { get; set; }
[JsonProperty("created_by_name")]
public string CreatedByName { get; set; }
[JsonProperty("custom")]
public Custom Custom { get; set; }
[JsonProperty("custom.lcf_dDtwGb41tpi8XkVMMgxdHxEJ92A7ujreRU1aPPZd95B")]
public string CustomInitialService { get; set; }
[JsonProperty("custom.lcf_fUNjcSq8bemwdQL0wogc3wgyxmz3ZD17fKdv8s4wkWV")]
public string CustomLeadOwner { get; set; }
[JsonProperty("custom.lcf_UfNWMxg2f7UU28rI9RAhTEAPWMyXU1UFZb5oNJEgR0K")]
public string CustomMarketingSource { get; set; }
[JsonProperty("custom.lcf_y37bo72LesrOBWuVPSoRfIazw5KflujnV81nGCfcjZ3")]
public string CustomDateCreated { get; set; }
[JsonProperty("custom.lcf_bzaGzJw0MsgtffSeHDQhYjfBmacMWxCiPM3DlqOlYZQ")]
public string CustomLocation { get; set; }
[JsonProperty("custom.lcf_1EE18uGReRLF6xqI45kWA3ijfSWJTe718FSgTiXdyEC")]
public string CustomStart { get; set; }
[JsonProperty("custom.lcf_E23dCjch37Zushwm1ZzPm3JXKXKJMZgYEYBjx5oabDF")]
public string CustomAppointment { get; set; }
[JsonProperty("date_created")]
public string DateCreated { get; set; }
[JsonProperty("date_updated")]
public string DateUpdated { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("display_name")]
public string DisplayName { get; set; }
[JsonProperty("html_url")]
public string HtmlUrl { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("integration_links")]
public IntegrationLink[] IntegrationLinks { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("opportunities")]
public Opportunity[] Opportunities { get; set; }
[JsonProperty("organization_id")]
public string OrganizationId { get; set; }
[JsonProperty("status_id")]
public string StatusId { get; set; }
[JsonProperty("status_label")]
public string StatusLabel { get; set; }
[JsonProperty("tasks")]
public object[] Tasks { get; set; }
[JsonProperty("updated_by")]
public string UpdatedBy { get; set; }
[JsonProperty("updated_by_name")]
public string UpdatedByName { get; set; }
[JsonProperty("url")]
public object Url { get; set; }
}
public partial class Opportunity
{
[JsonProperty("confidence")]
public long Confidence { get; set; }
[JsonProperty("contact_id")]
public object ContactId { get; set; }
[JsonProperty("contact_name")]
public object ContactName { get; set; }
[JsonProperty("created_by")]
public string CreatedBy { get; set; }
[JsonProperty("created_by_name")]
public string CreatedByName { get; set; }
[JsonProperty("date_created")]
public string DateCreated { get; set; }
[JsonProperty("date_lost")]
public object DateLost { get; set; }
[JsonProperty("date_updated")]
public string DateUpdated { get; set; }
[JsonProperty("date_won")]
public object DateWon { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("integration_links")]
public object[] IntegrationLinks { get; set; }
[JsonProperty("lead_id")]
public string LeadId { get; set; }
[JsonProperty("lead_name")]
public string LeadName { get; set; }
[JsonProperty("note")]
public string Note { get; set; }
[JsonProperty("organization_id")]
public string OrganizationId { get; set; }
[JsonProperty("status_id")]
public string StatusId { get; set; }
[JsonProperty("status_label")]
public string StatusLabel { get; set; }
[JsonProperty("status_type")]
public string StatusType { get; set; }
[JsonProperty("updated_by")]
public string UpdatedBy { get; set; }
[JsonProperty("updated_by_name")]
public string UpdatedByName { get; set; }
[JsonProperty("user_id")]
public string UserId { get; set; }
[JsonProperty("user_name")]
public string UserName { get; set; }
[JsonProperty("value")]
public long Value { get; set; }
[JsonProperty("value_currency")]
public string ValueCurrency { get; set; }
[JsonProperty("value_formatted")]
public string ValueFormatted { get; set; }
[JsonProperty("value_period")]
public string ValuePeriod { get; set; }
}
public partial class Custom
{
[JsonProperty("Date Created")]
public string DateCreated { get; set; }
[JsonProperty("Initial Service")]
public string InitialService { get; set; }
[JsonProperty("Lead Owner")]
public string LeadOwner { get; set; }
[JsonProperty("Marketing Source")]
public string MarketingSource { get; set; }
[JsonProperty("Location")]
public string Location { get; set; }
}
public class Email
{
[JsonProperty("email")]
public string EmailValue { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
public partial class Contact
{
[JsonProperty("created_by")]
public string CreatedBy { get; set; }
[JsonProperty("date_created")]
public string DateCreated { get; set; }
[JsonProperty("date_updated")]
public string DateUpdated { get; set; }
[JsonProperty("emails")]
public Email[] Emails { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("integration_links")]
public IntegrationLink[] IntegrationLinks { get; set; }
[JsonProperty("lead_id")]
public string LeadId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("organization_id")]
public string OrganizationId { get; set; }
[JsonProperty("phones")]
public Phone[] Phones { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("updated_by")]
public string UpdatedBy { get; set; }
[JsonProperty("urls")]
public object[] Urls { get; set; }
}
public partial class Phone
{
[JsonProperty("phone_formatted")]
public string PhoneFormatted { get; set; }
[JsonProperty("phone")]
public string PhoneNumber { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
public partial class IntegrationLink
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
public partial class Welcome
{
public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Converter.Settings);
}
In cases like this I find the query syntax more convenient than the fluent syntax, precisely because in nested SelectMany queries the outer items are accessible without needing to manually create intermediate anonymous types for passing values into the inner loop.
Thus:
var query = from d in json.Data
from c in d.Contacts
from e in c.Emails
select new { Email = e.EmailValue, LeadId = c.LeadId };
var emails = query.ToList();
This avoids the need to "go up" from the inner item to the outer.
Sample fiddle.
Here is my JSON:
{
"data": [
{
"addresses": [],
"contacts": [
{
"created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"date_created": "2017-12-03T05:42:30.737000+00:00",
"date_updated": "2017-12-03T05:45:32.227000+00:00",
"emails": [
{
"email": "testemail#testemail.com",
"type": "office"
}
],
"id": "cont_kH9tcx970T3ZTGKPPP2vh5u3Ha8P9Rjz6gGqflgzwvy",
"integration_links": [
{
"name": "LinkedIn Search",
"url": "https://www.linkedin.com/search/results/index/?keywords=Test%20Woodard"
}
],
"lead_id": "lead_12Rz7R2TrWmwUhCGVTRh8rt6A8hokaXgujSEPlfoWpD",
"name": "Test User",
"organization_id": "orga_iFnIMLDbvGevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
"phones": [
{
"phone": "+15558675309",
"phone_formatted": "+1 555-867-5309",
"type": "office"
}
],
"title": "",
"updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"urls": []
}
],
"created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"created_by_name": "Test User",
"custom": {
"Date Created": "2017-12-03",
"Initial Service": "Men's Health",
"Lead Owner": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"Marketing Source": "Bing"
},
"custom.lcf_UfNWMxg2f7UU28rI9RAhTEAPWMyXU1UFZb5oNJEgR0K": "Bing",
"custom.lcf_dDtwGb41tpi8XkVMMgxdHxEJ92A7ujreRU1aPPZd95B": "Chiropractor",
"custom.lcf_fUNjcSq8bemwdQL0wogc3wgyxmz3ZD17fKdv8s4wkWV": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"custom.lcf_y37bo72LesrOBWuVPSoRfIazw5KflujnV81nGCfcjZ3": "2017-12-03",
"date_created": "2017-12-03T05:42:30.733000+00:00",
"date_updated": "2017-12-03T05:45:32.234000+00:00",
"description": "",
"display_name": "test",
"html_url": "https://app.close.io/lead/lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpG/",
"id": "lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpD",
"integration_links": [
{
"name": "Google Search",
"url": "http://google.com/search?q=test"
}
],
"name": "test",
"opportunities": [
{
"confidence": 50,
"contact_id": null,
"contact_name": null,
"created_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"created_by_name": "Test User",
"date_created": "2017-12-03T05:44:31.131000+00:00",
"date_lost": null,
"date_updated": "2017-12-03T05:44:31.131000+00:00",
"date_won": null,
"id": "oppo_xQ5S1dHMjDWoeUBAigtyiwuwFUkxtbxHURQX5UaL7fT",
"integration_links": [],
"lead_id": "lead_12Rz7R2TrWmwUhCFVTRh8rt6A8hokaXgujSEPlfoWpD",
"lead_name": "test",
"note": "New Lead",
"organization_id": "orga_iFnIMLDbvNevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
"status_id": "stat_SwQmzqoIqIt20j9YBDxIYem11GyZPGL30G7PdkWYdvG",
"status_label": "Chiropractor",
"status_type": "active",
"updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"updated_by_name": "Test User",
"user_id": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"user_name": "Test User",
"value": 140000,
"value_currency": "USD",
"value_formatted": "$1,400",
"value_period": "one_time"
}
],
"organization_id": "orga_iFnIMLDbvNevDrXMHYQSbYnLu1GjrdM2TEWWsCoraJH",
"status_id": "stat_auhCEJZNhaUnX9DHdrCaZ5r5mhpqxjfaE1hdwnPz6xx",
"status_label": "Potential",
"tasks": [],
"updated_by": "user_C8ptFaOBRGnsYadWFUZCRCYXRnuV5Ch8Lgr9LKXz7zG",
"updated_by_name": "Test User",
"url": null
}
],
"has_more": false,
"total_results": 1
}
My Classes:
public partial class Welcome
{
[JsonProperty("data")]
public Datum[] Data { get; set; }
[JsonProperty("has_more")]
public bool HasMore { get; set; }
[JsonProperty("total_results")]
public long TotalResults { get; set; }
}
public partial class Datum
{
[JsonProperty("addresses")]
public object[] Addresses { get; set; }
[JsonProperty("contacts")]
public Contact[] Contacts { get; set; }
[JsonProperty("created_by")]
public string CreatedBy { get; set; }
[JsonProperty("created_by_name")]
public string CreatedByName { get; set; }
[JsonProperty("custom")]
public Custom Custom { get; set; }
[JsonProperty("custom.lcf_dDtwGb41tpi8XkVMMgxdHxEJ92A7ujreRU1aPPZd95B")]
public string CustomInitialService { get; set; }
[JsonProperty("custom.lcf_fUNjcSq8bemwdQL0wogc3wgyxmz3ZD17fKdv8s4wkWV")]
public string CustomLeadOwner { get; set; }
[JsonProperty("custom.lcf_UfNWMxg2f7UU28rI9RAhTEAPWMyXU1UFZb5oNJEgR0K")]
public string CustomMarketingSource { get; set; }
[JsonProperty("custom.lcf_y37bo72LesrOBWuVPSoRfIazw5KflujnV81nGCfcjZ3")]
public string CustomDateCreated { get; set; }
[JsonProperty("date_created")]
public string DateCreated { get; set; }
[JsonProperty("date_updated")]
public string DateUpdated { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("display_name")]
public string DisplayName { get; set; }
[JsonProperty("html_url")]
public string HtmlUrl { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("integration_links")]
public IntegrationLink[] IntegrationLinks { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("opportunities")]
public Opportunity[] Opportunities { get; set; }
[JsonProperty("organization_id")]
public string OrganizationId { get; set; }
[JsonProperty("status_id")]
public string StatusId { get; set; }
[JsonProperty("status_label")]
public string StatusLabel { get; set; }
[JsonProperty("tasks")]
public object[] Tasks { get; set; }
[JsonProperty("updated_by")]
public string UpdatedBy { get; set; }
[JsonProperty("updated_by_name")]
public string UpdatedByName { get; set; }
[JsonProperty("url")]
public object Url { get; set; }
}
public partial class Opportunity
{
[JsonProperty("confidence")]
public long Confidence { get; set; }
[JsonProperty("contact_id")]
public object ContactId { get; set; }
[JsonProperty("contact_name")]
public object ContactName { get; set; }
[JsonProperty("created_by")]
public string CreatedBy { get; set; }
[JsonProperty("created_by_name")]
public string CreatedByName { get; set; }
[JsonProperty("date_created")]
public string DateCreated { get; set; }
[JsonProperty("date_lost")]
public object DateLost { get; set; }
[JsonProperty("date_updated")]
public string DateUpdated { get; set; }
[JsonProperty("date_won")]
public object DateWon { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("integration_links")]
public object[] IntegrationLinks { get; set; }
[JsonProperty("lead_id")]
public string LeadId { get; set; }
[JsonProperty("lead_name")]
public string LeadName { get; set; }
[JsonProperty("note")]
public string Note { get; set; }
[JsonProperty("organization_id")]
public string OrganizationId { get; set; }
[JsonProperty("status_id")]
public string StatusId { get; set; }
[JsonProperty("status_label")]
public string StatusLabel { get; set; }
[JsonProperty("status_type")]
public string StatusType { get; set; }
[JsonProperty("updated_by")]
public string UpdatedBy { get; set; }
[JsonProperty("updated_by_name")]
public string UpdatedByName { get; set; }
[JsonProperty("user_id")]
public string UserId { get; set; }
[JsonProperty("user_name")]
public string UserName { get; set; }
[JsonProperty("value")]
public long Value { get; set; }
[JsonProperty("value_currency")]
public string ValueCurrency { get; set; }
[JsonProperty("value_formatted")]
public string ValueFormatted { get; set; }
[JsonProperty("value_period")]
public string ValuePeriod { get; set; }
}
public partial class Custom
{
[JsonProperty("Date Created")]
public string DateCreated { get; set; }
[JsonProperty("Initial Service")]
public string InitialService { get; set; }
[JsonProperty("Lead Owner")]
public string LeadOwner { get; set; }
[JsonProperty("Marketing Source")]
public string MarketingSource { get; set; }
}
public partial class Contact
{
[JsonProperty("created_by")]
public string CreatedBy { get; set; }
[JsonProperty("date_created")]
public string DateCreated { get; set; }
[JsonProperty("date_updated")]
public string DateUpdated { get; set; }
[JsonProperty("emails")]
public object[] Emails { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("integration_links")]
public IntegrationLink[] IntegrationLinks { get; set; }
[JsonProperty("lead_id")]
public string LeadId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("organization_id")]
public string OrganizationId { get; set; }
[JsonProperty("phones")]
public Phone[] Phones { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("updated_by")]
public string UpdatedBy { get; set; }
[JsonProperty("urls")]
public object[] Urls { get; set; }
}
public partial class Phone
{
[JsonProperty("phone_formatted")]
public string PhoneFormatted { get; set; }
[JsonProperty("phone")]
public string PurplePhone { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
public partial class IntegrationLink
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
public partial class Welcome
{
public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Welcome self) => JsonConvert.SerializeObject(self, Converter.Settings);
}
public class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
};
}
My Code:
var json = JsonConvert.DeserializeObject<Welcome>(html);
foreach (var j in json.Data)
{
foreach (var v in j.Contacts)
{
Console.WriteLine(v.Emails[0]);
}
}
So once I've deserialized the object I've tried using LINQ to get the email address out of the JSON using the objects, I can't navigate that far in and I'm not sure what's the best cleanest way to navigate for emails and phone numbers in the deserialized JSON.
First, for some reason you did not define a data model for your Email data:
public partial class Contact
{
// Initial properties
[JsonProperty("emails")]
public object[] Emails { get; set; }
// Additional properties.
Let's fix that with help from https://jsonutils.com/:
public partial class Contact
{
// Initial properties as before.
[JsonProperty("emails")]
public Email[] Emails { get; set; }
// Other properties as before
}
public class Email
{
[JsonProperty("email")]
public string EmailValue { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
Now you can iterate through all email and phone values by using SelectMany to create a final list:
var emails = json
// Enumerate through all data
.Data
// Enumerate through all contacts of all data
.SelectMany(d => d.Contacts)
// Enumerate through all emails of all contacts
.SelectMany(c => c.Emails)
// Get email value
.Select(e => e.EmailValue)
// Materialize as a list.
.ToList();
And
var phones = json
// Enumerate through all data
.Data
// Enumerate through all contacts of all data
.SelectMany(d => d.Contacts)
// Enumerate through all phones of all contacts
.SelectMany(c => c.Phones)
// Get phone number. But why ever did you choose to call it PurplePhone!?
.Select(p => p.PurplePhone)
// Materialize as a list.
.ToList();
Then, if you do:
Console.WriteLine("Emails: {0}", JsonConvert.SerializeObject(emails));
Console.WriteLine("Phones: {0}", JsonConvert.SerializeObject(phones));
The result is
Emails: ["testemail#testemail.com"]
Phones: ["+15558675309"]
Sample fiddle.
I have received a json string and i need help mapping that to an object
currently i am using:
string request = webClient.DownloadString(url);
which returns a json string of invoices:
"{\"invoices\":[
{\"url\":\"https://api.freeagent.com/v2/invoices/0000001\",\"contact\":\"https://api.freeagent.com/v2/contacts/000001\",\"dated_on\":\"2010-10-29\",\"due_on\":\"2010-11-28\",\"reference\":\"0001\",\"currency\":\"GBP\",\"exchange_rate\":\"1.0\",\"net_value\":\"60.0\",\"sales_tax_value\":\"68.0\",\"total_value\":\"528.0\",\"paid_value\":\"528.0\",\"due_value\":\"0.0\",\"status\":\"Paid\",\"omit_header\":false,\"payment_terms_in_days\":30,\"paid_on\":\"2011-11-14\"},{\"url\":\"https://api.freeagent.com/v2/invoices/0000002\",\"contact\":\"https://api.freeagent.com/v2/contacts/000002\",\"dated_on\":\"2010-11-19\",\"due_on\":\"2010-12-19\",\"reference\":\"0002\",\"currency\":\"GBP\",\"exchange_rate\":\"1.0\",\"net_value\":\"80.0\",\"sales_tax_value\":\"6.5\",\"total_value\":\"326.5\",\"paid_value\":\"650.0\",\"due_value\":\"76.5\",\"status\":\"Overdue\",\"comments\":\"Work\",\"omit_header\":false,\"payment_terms_in_days\":30}]}"
I have an invoice class:
public class Invoices
{
public string url { get; set; }
public string project { get; set; } //--
public string contact { get; set; } //--
public string dated_on { get; set; } //--
public string due_on { get; set; } //--
public string paid_on { get; set; }
public string reference { get; set; } //--
public string currency { get; set; } //--
public string exchange_rate { get; set; } //--
public string net_value { get; set; }
public string sales_tax_value { get; set; }
public string total_value { get; set; }
public string paid_value { get; set; }
public string due_value { get; set; }
public string discount_percent { get; set; }
public string status { get; set; }
public string comments { get; set; } //--
public string omit_header { get; set; }
public string payment_terms_in_days { get; set; } //--
public string ec_status { get; set; } //need to add fields
public string written_off_date { get; set; }
}
Different invoices can return different information which is why there is a lot of values in the class that may not be in the json string.
I have tried these approaches but keep getting errors:
List<Invoices> list = JsonConvert.DeserializeObject<List<Invoices>>(request);
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(request);
Could someone show me how to get the information shown in the string out?
Edit:
I have also tried:
var info = JsonConvert.DeserializeObject(request);
And that return this as a jObect
{
"invoices": [
{
"url": "https://api.freeagent.com/v2/invoices/000000",
"contact": "https://api.freeagent.com/v2/contacts/000000",
"dated_on": "2010-10-29",
"due_on": "2010-11-28",
"reference": "0000",
"currency": "GBP",
"exchange_rate": "1.0",
"net_value": "960.0",
"sales_tax_value": "568.0",
"total_value": "528.0",
"paid_value": "528.0",
"due_value": "0.0",
"status": "Paid",
"omit_header": false,
"payment_terms_in_days": 30,
"paid_on": "2011-11-14"
},
{
"url": "https://api.freeagent.com/v2/invoices/000000",
"contact": "https://api.freeagent.com/v2/contacts/000000",
"dated_on": "2010-11-19",
"due_on": "2010-12-19",
"reference": "0000",
"currency": "GBP",
"exchange_rate": "1.0",
"net_value": "980.0",
"sales_tax_value": "46.5",
"total_value": "326.5",
"paid_value": "650.0",
"due_value": "76.5",
"status": "Overdue",
"comments": "Work",
"omit_header": false,
"payment_terms_in_days": 30
}
}
The classes (as for the Json u posted) should look like this:
public class Invoice
{
public string url { get; set; }
public string contact { get; set; }
public string dated_on { get; set; }
public string due_on { get; set; }
public string reference { get; set; }
public string currency { get; set; }
public string exchange_rate { get; set; }
public string net_value { get; set; }
public string sales_tax_value { get; set; }
public string total_value { get; set; }
public string paid_value { get; set; }
public string due_value { get; set; }
public string status { get; set; }
public bool omit_header { get; set; }
public int payment_terms_in_days { get; set; }
public string paid_on { get; set; }
public string comments { get; set; }
}
public class RootObject
{
public List<Invoice> invoices { get; set; }
}
And:
RootObject list = JsonConvert.DeserializeObject<RootObject>(request);
The RootObject object contains a list of invoices
Json: (there is a ] missing on your version, near the end of the Json to close the array)
{
"invoices": [
{
"url": "https://api.freeagent.com/v2/invoices/000000",
"contact": "https://api.freeagent.com/v2/contacts/000000",
"dated_on": "2010-10-29",
"due_on": "2010-11-28",
"reference": "0000",
"currency": "GBP",
"exchange_rate": "1.0",
"net_value": "960.0",
"sales_tax_value": "568.0",
"total_value": "528.0",
"paid_value": "528.0",
"due_value": "0.0",
"status": "Paid",
"omit_header": false,
"payment_terms_in_days": 30,
"paid_on": "2011-11-14"
},
{
"url": "https://api.freeagent.com/v2/invoices/000000",
"contact": "https://api.freeagent.com/v2/contacts/000000",
"dated_on": "2010-11-19",
"due_on": "2010-12-19",
"reference": "0000",
"currency": "GBP",
"exchange_rate": "1.0",
"net_value": "980.0",
"sales_tax_value": "46.5",
"total_value": "326.5",
"paid_value": "650.0",
"due_value": "76.5",
"status": "Overdue",
"comments": "Work",
"omit_header": false,
"payment_terms_in_days": 30
}]
}
Could someone show me how to get the information shown in the string
out?
You can do this (dynamic):
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
dynamic lst = oSerializer.Deserialize<dynamic>(request );
Console.WriteLine(lst["invoices"][0]["due_on"]); <--put here whatever you want.
Here for example , I read the value of the first item in array :