Related
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; }
}
I'm receiving a JSON string in C#, like this :
{
"Id": "617723",
"Acronym": "",
"FirstName": "XXXXX",
"LastName": "XXXXX",
"Groupe": {
"Code": "XXXXX",
"Traductions": {
"French": "",
"English": "XXXXX"
}
},
"BusinessUnit": {
"Code": "XXXXX",
"Traductions": {
"French": "",
"English": "XXXXX"
}
},
"Team": {
"Code": null,
"Traductions": {
"French": "",
"English": null
}
},
"Title": {
"Code": null,
"Traductions": {
"French": "",
"English": "XXXXX"
}
},
"Title2": {
"Code": null,
"Traductions": {
"French": "",
"English": null
}
},
"JobCategory": {
"Code": "XXXXX",
"Traductions": {
"French": "",
"English": "XXXXX"
}
},
"PhoneList": [],
"DateHired": "XXXXX",
"DateTerminated": "XXXXX",
"Gender": "XXXXX",
"ManagerId": "XXXXX",
"ManagerAcronym": "XXXXX",
"IsManager": false,
"Email": null,
"CarLicense": null,
"MyTeam": [],
"HomeBase": {
"Code": "XXXXX",
"Traductions": {
"French": "XXXXX",
"English": "XXXXX"
}
},
"Country": {
"Code": "XXXXX",
"Traductions": {
"French": "XXXXXX",
"English": "XXXXX"
}
},
"State": {
"Code": "XXXXX",
"Traductions": {
"French": "XXXXX",
"English": "XXXXX"
}
},
"City": {
"Code": "XXXXX",
"Traductions": {
"French": "XXXXX",
"English": "XXXXX"
}
},
"ShirtSize": "",
"LanguageAddressBook": "XXXXX",
"LanguagePrefered": null,
"Local": null,
"Mailbox": null,
"HomeBusinessUnit": "1",
"JobType": "XXXXXX",
"UnionCode": "",
"ProfessionalTitle": {
"Code": null,
"Traductions": {
"French": "",
"English": null
}
},
"IconEmailActif": true,
"IconSkypeActif": true
}
I want to convert it in a C# Object, so I made my Model like this :
public class UsersJson
{
public string Acronym { get; set; }
public string[] BusinessUnit { get; set; }
public string CarLicense { get; set; }
public string[] City { get; set; }
public string[] Country { get; set; }
public string DateHired { get; set; }
public string DateTerminated { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string Gender { get; set; }
public string[] Groupe { get; set; }
public string[] HomeBase { get; set; }
public string HomeBusinessUnit { get; set; }
public bool IconEmailActif { get; set; }
public bool IconSkypeActif { get; set; }
public string Id { get; set; }
public bool IsManager { get; set; }
public string[] JobCategory { get; set; }
public string JobType { get; set; }
public string LanguageAddressBook { get; set; }
public string LanguagePrefered { get; set; }
public string LastName { get; set; }
public string Local { get; set; }
public string Mailbox { get; set; }
public string ManagerAcronym { get; set; }
public string ManagerId { get; set; }
public string[] MyTeam { get; set; }
public string[] PhoneList { get; set; }
public string[] ProfessionalTitle { get; set; }
public string ShirtSize { get; set; }
public string[] State { get; set; }
public string[] Team { get; set; }
public string[] Title { get; set; }
public string[] Title2 { get; set; }
public string UnionCode { get; set; }
}
When I try to Deserialize it into a List<UsersJson>, I get the following error :
Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.String[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path '[0].Groupe.Code', line 1, position 87."
So, how should I declare the property Group if it's not a string[] ?
Use the correct classes. I followed the steps outlined here and refactored a bit:
RootObject r = JsonConvert.DeserializeObject<RootObject>(json);
public class Traductions
{
public string French { get; set; }
public string English { get; set; }
}
public class Groupe
{
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class BusinessUnit
{
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class Team
{
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class Title
{
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class JobCategory
{
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class HomeBase
{
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class Country
{
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class State
{
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class City
{
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class ProfessionalTitle
{
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class RootObject
{
public string Id { get; set; }
public string Acronym { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Groupe Groupe { get; set; }
public BusinessUnit BusinessUnit { get; set; }
public Team Team { get; set; }
public Title Title { get; set; }
public Title Title2 { get; set; }
public JobCategory JobCategory { get; set; }
public List<object> PhoneList { get; set; }
public string DateHired { get; set; }
public string DateTerminated { get; set; }
public string Gender { get; set; }
public string ManagerId { get; set; }
public string ManagerAcronym { get; set; }
public bool IsManager { get; set; }
public string Email { get; set; }
public string CarLicense { get; set; }
public List<object> MyTeam { get; set; }
public HomeBase HomeBase { get; set; }
public Country Country { get; set; }
public State State { get; set; }
public City City { get; set; }
public string ShirtSize { get; set; }
public string LanguageAddressBook { get; set; }
public string LanguagePrefered { get; set; }
public string Local { get; set; }
public string Mailbox { get; set; }
public string HomeBusinessUnit { get; set; }
public string JobType { get; set; }
public string UnionCode { get; set; }
public ProfessionalTitle ProfessionalTitle { get; set; }
public bool IconEmailActif { get; set; }
public bool IconSkypeActif { get; set; }
}
You'll need another couple of classes with the Code and Traductions properties.
public class Groupe {
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class Traductions {
public string French { get; set; }
public string English { get; set; }
}
Use Groupe in place of string[] in your base class and you should be golden :)
The accepted answer works, but I feel it has a lot of code-repetition. You only need two other model classes for this to work:
public class Traductions
{
public string French { get; set; }
public string English { get; set; }
}
public class CodeTraduction
{
public string Code { get; set; }
public Traductions Traductions { get; set; }
}
public class RootObject
{
public string Id { get; set; }
public string Acronym { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public CodeTraduction Groupe { get; set; }
public CodeTraduction BusinessUnit { get; set; }
public CodeTraduction Team { get; set; }
public CodeTraduction Title { get; set; }
public CodeTraduction Title2 { get; set; }
public CodeTraduction JobCategory { get; set; }
public List<object> PhoneList { get; set; }
public string DateHired { get; set; }
public string DateTerminated { get; set; }
public string Gender { get; set; }
public string ManagerId { get; set; }
public string ManagerAcronym { get; set; }
public bool IsManager { get; set; }
public string Email { get; set; }
public string CarLicense { get; set; }
public List<object> MyTeam { get; set; }
public CodeTraduction HomeBase { get; set; }
public CodeTraduction Country { get; set; }
public CodeTraduction State { get; set; }
public CodeTraduction City { get; set; }
public string ShirtSize { get; set; }
public string LanguageAddressBook { get; set; }
public string LanguagePrefered { get; set; }
public string Local { get; set; }
public string Mailbox { get; set; }
public string HomeBusinessUnit { get; set; }
public string JobType { get; set; }
public string UnionCode { get; set; }
public CodeTraduction ProfessionalTitle { get; set; }
public bool IconEmailActif { get; set; }
public bool IconSkypeActif { get; set; }
}
Using your example JSON, you would deserialize it like this:
var item = JsonConvert.DeserializeObject<RootObject>(json);
You can create separate classes if you wish, but keep a single base-class CodeTraduction, for example:
public class Groupe : CodeTraduction
{
//Add any "Groupe" specific properties here
}
For future reference, you can also use Paste Special. You copy the JSON file(Ctrl+C) and add a new class file, if you dont already have one. Then you go in to Edit(at the top left of VS) and hover your cursor over Paste Special, you will get two options, one for XML as Class or JSON as Class.
Hope it helps you and others in the future. :)
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.
Here is the call to DeserializeObject:
listrootobject obj = JsonConvert.DeserializeObject<listrootobject>(json);
Here is Json .
{
"so:MemberProfileDataSet": {
"#xmlns:moso": "http://schema.socloud.com/1/MemberProfileDataSet.xsd",
"Member": {
"#xmlns": "http://schema.socloud.com/1/MemberProfileDataSet.xsd",
"PartyId": "63",
"PartyTypeName": "Employee",
"RoleId": "1310",
"BusinessUnitCode": "95",
"CardId": null,
"PostalContact": {
"PartyId": "63",
"TypeName": "Mailing Address",
"Address1": "100 Main Ave",
"Address2": null,
"Address3": null,
"City": "Arlington",
"State": "VA",
"PostalCode": "22206"
},
"PhoneContact": [{
"PartyId": "63",
"TypeName": "Cell",
"CountryCode": "1",
"Telephone": "(555) 555-5555",
"AdditionalData": null,
"TextMessageOK": "false"
}, {
"PartyId": "63",
"TypeName": "Home",
"CountryCode": "1",
"Telephone": null,
"AdditionalData": null,
"TextMessageOK": "false"
}],
"Property": [{
"PartyId": "63",
"Name": "First Name",
"Value": "Katie"
}, {
"PartyId": "63",
"Name": "Last Name",
"Value": "Rodriguez"
}, {
"PartyId": "63",
"Name": "Payroll ID",
"Value": null
}, {
"PartyId": "63",
"Name": "Lookup Initials",
"Value": null
}, {
"PartyId": "63",
"Name": "Date of Birth",
"Value": null
}, {
"PartyId": "63",
"Name": "Hire Date",
"Value": null
}, {
"PartyId": "63",
"Name": "Termination Date",
"Value": null
}, {
"PartyId": "63",
"Name": "Gender",
"Value": null
}]
}
}
}
Here is C# Class
public class PostalContact
{
public string PartyId { get; set; }
public string TypeName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
}
public class EmailContact
{
public string PartyId { get; set; }
public string TypeName { get; set; }
public string EmailAddress { get; set; }
public string EmailOptOut { get; set; }
}
public class PhoneContact
{
public string PartyId { get; set; }
public string TypeName { get; set; }
public string CountryCode { get; set; }
public string Telephone { get; set; }
public string AdditionalData { get; set; }
public string TextMessageOK { get; set; }
}
public class Property
{
public string PartyId { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
//public class rootobject
//{
// public List<Member> Members { get; set; }
//}
public class Member
{
public string PartyId { get; set; }
public string PartyTypeName { get; set; }
public string RoleId { get; set; }
public string BusinessUnitCode { get; set; }
public string CardId { get; set; }
public PostalContact PostalContact { get; set; }
public EmailContact EmailContact { get; set; }
public List<PhoneContact> PhoneContact { get; set; }
public List<Property> Property { get; set; }
public string _xmlns { get; set; }
}
public class MemberProfileDataSet
{
public Member Member { get; set; }
public string __invalid_name___xmlns_moso { get; set; }
public string __prefix { get; set; }
}
public class listrootobject
{
public List<MemberProfileDataSet> rootobjects { get; set; }
}
public class rootobject
{
public MemberProfileDataSet MemberProfileDataSet { get; set; }
}
Use http://json2csharp.com/ to generate and write your C# classes as the generated classes from the website. Lastly you parse the rootObject as below.
But you have a problem because the property names it generates are invalid in C# and you cannot create a C# class with those names. But the names must match to de-serialize. So you need to remove the invalid characters or re-name them to meet the C# CLR naming requirements.Then create a C# class of the properly formatted string. After which you can de-serialized.
For instance I generated C# object from the original string and I had a property name as
public SoMemberProfileDataSet __invalid_name__so:MemberProfileDataSet { get; set; }
This is invalid in C# but you would need to format this in the string to something valid e.g.
public SoMemberProfileDataSet MemberProfileDataSet { get; set; }
by renaming the json string or getting the properties you want from the string and re-constructing the json properly before de serializing.
Show me the code
As an example, I have combined strings between colons and removed the # symbol so that I created a valid C# object. And it de-seralizes. Please see changes in the json string below. So please format your json string and you will have it.
string json = "{\"soMemberProfileDataSet\": {\"xmlnsmoso\": \"http://schema.socloud.com/1/MemberProfileDataSet.xsd\",\"Member\": {\"xmlns\": \"http://schema.socloud.com/1/MemberProfileDataSet.xsd\",\"PartyId\": \"63\",\"PartyTypeName\": \"Employee\",\"RoleId\": \"1310\",\"BusinessUnitCode\": \"95\",\"CardId\": null,\"PostalContact\": {\"PartyId\": \"63\",\"TypeName\": \"Mailing Address\",\"Address1\": \"100 Main Ave\",\"Address2\": null,\"Address3\": null,\"City\": \"Arlington\",\"State\": \"VA\",\"PostalCode\": \"22206\"},\"PhoneContact\": [{\"PartyId\": \"63\",\"TypeName\": \"Cell\",\"CountryCode\": \"1\",\"Telephone\": \"(555) 555-5555\",\"AdditionalData\": null,\"TextMessageOK\": \"false\"}, {\"PartyId\": \"63\",\"TypeName\": \"Home\",\"CountryCode\": \"1\",\"Telephone\": null,\"AdditionalData\": null,\"TextMessageOK\": \"false\"}],\"Property\": [{\"PartyId\": \"63\",\"Name\": \"First Name\",\"Value\": \"Katie\"}, {\"PartyId\": \"63\",\"Name\": \"Last Name\",\"Value\": \"Rodriguez\"}, {\"PartyId\": \"63\",\"Name\": \"Payroll ID\",\"Value\": null}, {\"PartyId\": \"63\",\"Name\": \"Lookup Initials\",\"Value\": null}, {\"PartyId\": \"63\",\"Name\": \"Date of Birth\",\"Value\": null}, {\"PartyId\": \"63\",\"Name\": \"Hire Date\",\"Value\": null}, {\"PartyId\": \"63\",\"Name\": \"Termination Date\",\"Value\": null}, {\"PartyId\": \"63\",\"Name\": \"Gender\",\"Value\": null}]}}}";
var listrootobject = JsonConvert.DeserializeObject<RootObject>(json);
Your class should now look like as below, no more invalid property names after formatting
public class PostalContact
{
public string PartyId { get; set; }
public string TypeName { get; set; }
public string Address1 { get; set; }
public object Address2 { get; set; }
public object Address3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
}
public class PhoneContact
{
public string PartyId { get; set; }
public string TypeName { get; set; }
public string CountryCode { get; set; }
public string Telephone { get; set; }
public object AdditionalData { get; set; }
public string TextMessageOK { get; set; }
}
public class Property
{
public string PartyId { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
public class Member
{
public string xmlns { get; set; }
public string PartyId { get; set; }
public string PartyTypeName { get; set; }
public string RoleId { get; set; }
public string BusinessUnitCode { get; set; }
public object CardId { get; set; }
public PostalContact PostalContact { get; set; }
public List<PhoneContact> PhoneContact { get; set; }
public List<Property> Property { get; set; }
}
public class SoMemberProfileDataSet
{
public string xmlnsmoso { get; set; }
public Member Member { get; set; }
}
public class RootObject
{
public SoMemberProfileDataSet soMemberProfileDataSet { get; set; }
}