Get only one property from Json in deserialize (C#) - c#

I have json that come from API
Here is part of it
{
"Area": "Werrington, Peterborough",
"MetaData": {
"CanonicalName": "pe4-werrington,peterborough",
"District": "PE4",
"Postcode": "PE46QR",
"Area": "Werrington, Peterborough",
"Latitude": 52.609645,
"Longitude": -0.268349,
"ResultCount": 113,
"SearchedTerms": null
},
"Restaurants": [
{
"Id": 65016,
"Name": "Grill & Krispy",
"UniqueName": "Grill-and-Krispy-pe1",
"Address": {
"City": "Peterborough",
"FirstLine": "20 Westgate",
"Postcode": "PE1 2SY",
"Latitude": 52.574544,
"Longitude": -0.243271
},
"City": "Peterborough",
"Postcode": "PE1 2SY",
"Latitude": 0.0,
"Longitude": 0.0,
"Rating": {
"Count": 1726,
"Average": 4.23,
"StarRating": 4.23
},
"RatingStars": 4.23,
"NumberOfRatings": 1726,
"RatingAverage": 4.23,
"Description": "",
"Url": "https://www.just-eat.co.uk/restaurants-Grill-and-Krispy-pe1",
"LogoUrl": "http://d30v2pzvrfyzpo.cloudfront.net/uk/images/restaurants/65016.gif",
"IsTestRestaurant": false,
"IsHalal": false,
"IsNew": false,
"ReasonWhyTemporarilyOffline": "",
"DriveDistance": 2.6,
"DriveInfoCalculated": true,
"IsCloseBy": false,
"OfferPercent": 20.0,
"NewnessDate": "2016-11-03T12:58:00",
"OpeningTime": "2020-09-02T09:30:00Z",
"OpeningTimeUtc": null,
"OpeningTimeIso": "2020-09-02T09:30:00",
"OpeningTimeLocal": "2020-09-02T10:30:00",
"DeliveryOpeningTimeLocal": "2020-09-01T12:00:00",
"DeliveryOpeningTime": "2020-09-01T11:00:00Z",
"DeliveryOpeningTimeUtc": null,
"DeliveryStartTime": "2020-09-01T11:00:00Z",
"DeliveryTime": null,
"DeliveryTimeMinutes": null,
"DeliveryWorkingTimeMinutes": 40,
"DeliveryEtaMinutes": {
"Approximate": null,
"RangeLower": 30,
"RangeUpper": 45
},
"IsCollection": true,
"IsDelivery": true,
"IsFreeDelivery": false,
"IsOpenNowForCollection": true,
"IsOpenNowForDelivery": true,
"IsOpenNowForPreorder": false,
"IsOpenNow": true,
"IsTemporarilyOffline": false,
"DeliveryMenuId": 230763,
"CollectionMenuId": null,
"DeliveryZipcode": null,
"DeliveryCost": 0.0,
"MinimumDeliveryValue": 0.0,
"SecondDateRanking": 0.0,
"DefaultDisplayRank": 0,
"SponsoredPosition": 0,
"SecondDateRank": 0.0,
"Score": 113.0,
"IsTemporaryBoost": false,
"IsSponsored": true,
"IsPremier": false,
"HygieneRating": null,
"ShowSmiley": false,
"SmileyDate": null,
"SmileyElite": false,
"SmileyResult": null,
"SmileyUrl": null,
"SendsOnItsWayNotifications": false,
"BrandName": "",
"IsBrand": false,
"LastUpdated": "2020-09-01T11:16:19.144899"
}
]
}
I need to get only Restaurants part.
Here is how I try to do this
var baseUrl = "**********";
var client = new RestClient(baseUrl);
var request = new RestRequest($"restaurants/bypostcode/{input.PostCode}", Method.GET);
var response = await client.ExecuteTaskAsync(request);
var searchResult = JsonConvert.DeserializeObject<Restaurant>(response.Content);
And on deserialize I get this
{
"id": 0,
"name": null,
"uniqueName": null,
"address": null,
"city": null,
"postcode": null,
"latitude": 0,
"longitude": 0,
"rating": null,
"ratingStars": 0,
"numberOfRatings": 0,
"ratingAverage": 0,
"description": null,
"url": null,
"logoUrl": null,
"isTestRestaurant": false,
"isHalal": false,
"isNew": false,
"reasonWhyTemporarilyOffline": null,
"driveDistance": 0,
"driveInfoCalculated": false,
"isCloseBy": false,
"offerPercent": 0,
"newnessDate": "0001-01-01T00:00:00",
"openingTime": "0001-01-01T00:00:00",
"openingTimeUtc": null,
"openingTimeIso": "0001-01-01T00:00:00",
"openingTimeLocal": "0001-01-01T00:00:00",
"deliveryOpeningTimeLocal": "0001-01-01T00:00:00",
"deliveryOpeningTime": "0001-01-01T00:00:00",
"deliveryOpeningTimeUtc": null,
"deliveryStartTime": "0001-01-01T00:00:00",
"deliveryTime": null,
"deliveryTimeMinutes": null,
"deliveryWorkingTimeMinutes": 0,
"isCollection": false,
"isDelivery": false,
"isFreeDelivery": false,
"isOpenNowForCollection": false,
"isOpenNowForDelivery": false,
"isOpenNowForPreorder": false,
"isOpenNow": false,
"isTemporarilyOffline": false,
"deliveryMenuId": 0,
"collectionMenuId": null,
"deliveryZipcode": null,
"deliveryCost": 0,
"minimumDeliveryValue": 0,
"secondDateRanking": 0,
"defaultDisplayRank": 0,
"sponsoredPosition": 0,
"secondDateRank": 0,
"score": 0,
"isTemporaryBoost": false,
"isSponsored": false,
"isPremier": false,
"hygieneRating": null,
"showSmiley": false,
"smileyDate": null,
"smileyElite": false,
"smileyResult": null,
"smileyUrl": null,
"sendsOnItsWayNotifications": false,
"brandName": null,
"isBrand": false,
"lastUpdated": "0001-01-01T00:00:00",
"tags": null,
"deliveryChargeBands": null,
"badges": null,
"openingTimes": null,
"serviceableAreas": null
}
How I can fix this?

The JSON you're deserializing is not an instance of Restaurant. It's an instance of an object which has a property called Restaurants which is an array of, presumably, Restaurant objects.
Create that object structure:
public class RestaurantsInfo
{
public IEnumerable<Restaurant> Restaurants { get; set; }
}
And deserialize to that:
var searchResult = JsonConvert.DeserializeObject<RestaurantsInfo>(response.Content);

Related

can't put content from restsharp to db

I am working with some API in C# Winforms. Getting response successfully as a json. The problem is that when I deserialize it the output is just a big string like this:
{"orders": [
{
"id": 155971090,
"date_created": "2021-06-18T06:16:31.36202+03:00",
"date_modified": "2021-06-19T15:10:45.567327+03:00",
"client_first_name": "Олександр",
"client_second_name": "",
"client_last_name": "Бандура",
"client_id": 133374423,
"client_avg_rating": 5.0,
"email": "bandurao#ukr.net",
"phone": "+380996461421",
"delivery_option": {
"id": 13662439,
"name": "Доставка \"Нова Пошта\""
},
"delivery_address": "Ананьїв, №1: вул. Незалежності, 19",
"delivery_provider_data": {
"provider": "nova_poshta",
"type": "W2W",
"sender_warehouse_id": null,
"recipient_warehouse_id": "4049834c-e1c2-11e3-8c4a-0050568002cf",
"declaration_number": null
},
"delivery_cost": 0,
"payment_option": {
"id": 7451891,
"name": "Передоплата"
},
"payment_data": null,
"price": "169,72 грн.",
"full_price": "169,72 грн.",
"client_notes": "",
"products": [
{
"id": 1430223923,
"external_id": "513.4769",
"name": "Ремень 4L-240",
"name_multilang": {
"ru": "Ремень 4L-240",
"uk": "Ремінь 4L-240"
},
"sku": "4769",
"price": "21,76 грн.",
"quantity": 1.0,
"measure_unit": "шт.",
"image": "https://images.ua.prom.st/3169964688_w100_h100_remen-4l-240.jpg",
"url": "https://teomax.com.ua/p1430223923-remen-240.html",
"total_price": "21,76 грн.",
"cpa_commission": {
"amount": "1.00"
}
},
{
"id": 1430222732,
"external_id": "512.4825",
"name": "Ремень 240 PJ3",
"name_multilang": {
"ru": "Ремень 240 PJ3",
"uk": "Ремінь 240 PJ3"
},
"sku": "4825",
"price": "48,96 грн.",
"quantity": 1.0,
"measure_unit": "шт.",
"image": "https://images.ua.prom.st/3170015051_w100_h100_remen-240-pj3.jpg",
"url": "https://teomax.com.ua/p1430222732-remen-240-pj3.html",
"total_price": "48,96 грн.",
"cpa_commission": {
"amount": "2.25"
}
},
{
"id": 1430230819,
"external_id": "297.2885",
"name": "Масло \"двухтактное\" (2Т), 1л",
"name_multilang": {
"ru": "Масло \"двухтактное\" (2Т), 1л",
"uk": "Масло \"двотактне\" (2Т), 1л"
},
"sku": "2885",
"price": "99 грн.",
"quantity": 1.0,
"measure_unit": "шт.",
"image": "https://images.ua.prom.st/3169999571_w100_h100_maslo-dvuhtaktnoe-2t.jpg",
"url": "https://teomax.com.ua/p1430230819-maslo-dvuhtaktnoe.html",
"total_price": "99 грн.",
"cpa_commission": {
"amount": "4.55"
}
}
],
"status": "delivered",
"status_name": "Выполнен",
"source": "portal",
"price_with_special_offer": null,
"special_offer_discount": null,
"special_offer_promocode": null,
"has_order_promo_free_delivery": false,
"cpa_commission": {
"amount": "7.80",
"is_refunded": false
},
"utm": null
},
{
"id": 155896081,
"date_created": "2021-06-17T13:11:40.241146+03:00",
"date_modified": "2021-06-17T13:42:55.021203+03:00",
"client_first_name": "Антон",
"client_second_name": "",
"client_last_name": "Подосельник",
"client_id": 133299120,
"client_avg_rating": 5.0,
"email": "a.n.podoselnik#gmail.com",
"phone": "+380992764450",
"delivery_option": {
"id": 13662439,
"name": "Доставка \"Нова Пошта\""
},
"delivery_address": "Киев, №132 (до 30 кг): просп. Леся Курбаса, 16-А",
"delivery_provider_data": {
"provider": "nova_poshta",
"type": "W2W",
"sender_warehouse_id": null,
"recipient_warehouse_id": "51b6c251-7a06-11e4-acce-0050568002cf",
"declaration_number": null
},
"delivery_cost": 0,
"payment_option": {
"id": 7451890,
"name": "Готівкою"
},
"payment_data": null,
"price": "254,30 грн.",
"full_price": "254,30 грн.",
"client_notes": "",
"products": [
{
"id": 1430208419,
"external_id": "250.4391",
"name": "Подшипник шариковый 12*30*8",
"name_multilang": {
"ru": "Подшипник шариковый 12*30*8",
"uk": "Підшипник кульковий 12*30*8"
},
"sku": "4391",
"price": "50,86 грн.",
"quantity": 5.0,
"measure_unit": "шт.",
"image": "https://images.ua.prom.st/3169911780_w100_h100_podshipnik-sharikovyj-12308.jpg",
"url": "https://teomax.com.ua/p1430208419-podshipnik-sharikovyj-12308.html",
"total_price": "254,30 грн.",
"cpa_commission": {
"amount": "5.08"
}
}
],
"status": "canceled",
"status_name": "Отменен",
"source": "portal",
"price_with_special_offer": null,
"special_offer_discount": null,
"special_offer_promocode": null,
"has_order_promo_free_delivery": false,
"cpa_commission": {
"amount": "5.08",
"is_refunded": true
},
"utm": null
},
{
"id": 155881650,
"date_created": "2021-06-17T11:36:11.87828+03:00",
"date_modified": "2021-06-17T13:10:11.527256+03:00",
"client_first_name": "Антон",
"client_second_name": "",
"client_last_name": "Подосельник",
"client_id": 133299120,
"client_avg_rating": 5.0,
"email": "a.n.podoselnik#gmail.com",
"phone": "+380992764450",
"delivery_option": {
"id": 13662439,
"name": "Доставка \"Нова Пошта\""
},
"delivery_address": "Киев, №132 (до 30 кг): просп. Леся Курбаса, 16-А",
"delivery_provider_data": {
"provider": "nova_poshta",
"type": "W2W",
"sender_warehouse_id": null,
"recipient_warehouse_id": "51b6c251-7a06-11e4-acce-0050568002cf",
"declaration_number": null
},
"delivery_cost": 0,
"payment_option": {
"id": 7451890,
"name": "Готівкою"
},
"payment_data": null,
"price": "305,16 грн.",
"full_price": "305,16 грн.",
"client_notes": "",
"products": [
{
"id": 1430208419,
"external_id": "250.4391",
"name": "Подшипник шариковый 12*30*8",
"name_multilang": {
"ru": "Подшипник шариковый 12*30*8",
"uk": "Підшипник кульковий 12*30*8"
},
"sku": "4391",
"price": "50,86 грн.",
"quantity": 6.0,
"measure_unit": "шт.",
"image": "https://images.ua.prom.st/3169911780_w100_h100_podshipnik-sharikovyj-12308.jpg",
"url": "https://teomax.com.ua/p1430208419-podshipnik-sharikovyj-12308.html",
"total_price": "305,16 грн.",
"cpa_commission": {
"amount": "6.10"
}
}
],
"status": "canceled",
"status_name": "Отменен",
"source": "portal",
"price_with_special_offer": null,
"special_offer_discount": null,
"special_offer_promocode": null,
"has_order_promo_free_delivery": false,
"cpa_commission": {
"amount": "6.10",
"is_refunded": true
},
"utm": null
}
]}
My function to get this is like this:
public IRestResponse GetOrders()
{
var connection = new RestClient("https://my.prom.ua/api/v1/");
connection.UseNewtonsoftJson();
var request = new RestRequest("orders/list", Method.GET, DataFormat.None);
request.AddHeader("authorization", "Bearer token");
var response = connection.Get(request);
//var things = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content);
Console.WriteLine(response.Content);
return response;
}
Then I tried to make json object out of it and deserialize:
var jsonString = JToken.Parse(data.Content);
var obj = JObject.Parse(jsonString.ToString());
How can I make key value pair out of this and be able to put data into a db table?

Bi-annual events created using Graph API/SDK missing first instance

When I create the following event using the graph SDK, the first instance of the recurring event isn't created until May 4th, 2021:
var tmpEvent = new Microsoft.Graph.Event
{
Start = new Microsoft.Graph.DateTimeTimeZone
{
DateTime = "2020-05-04T16:00:00",
TimeZone = "Central Standard Time"
},
End = new Microsoft.Graph.DateTimeTimeZone
{
DateTime = "2020-05-04T17:00:00",
TimeZone = "Central Standard Time"
},
Subject = "Bi-Annual Event",
Body = new Microsoft.Graph.ItemBody
{
Content = "Trying to make a bi-annual event",
ContentType = Microsoft.Graph.BodyType.Text
},
Attendees = new List<Microsoft.Graph.Attendee>{
new Microsoft.Graph.Attendee
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "test.email.123#someTestDomain.org"
},
Type = Microsoft.Graph.AttendeeType.Required
}
},
Location = new Microsoft.Graph.Location
{
DisplayName = "the office"
},
Recurrence = new PatternedRecurrence
{
Pattern = new RecurrencePattern
{
DayOfMonth = 4,
Interval = 2,
Month = 5,
Type = RecurrencePatternType.AbsoluteYearly
},
Range = new RecurrenceRange
{
StartDate = new Date(2020, 5, 4),
Type = RecurrenceRangeType.NoEnd
}
}
};
var graphClient = await MicrosoftAuthenticationProvider.GetGraphClient(CALENDAR_CLIENT_ID, CALENDAR_CLIENT_SECRET, CALENDAR_REDIRECT_URI, CALENDAR_ACCESS_SCOPES, RefreshToken);
var savedEvent = await graphClient.Me.Events
.Request()
.AddAsync(tmpEvent);
Here is what the recurrence looks like in Outlook:
enter image description here
When I resave the recurrence/series in Outlook, the event appears (correctly) on May 4th, 2020.
Is this a bug with the graph SDK?
UPDATE:
Here is the body request I am sending:
{
"OriginalStartTimeZone": null,
"OriginalEndTimeZone": null,
"ResponseStatus": null,
"ICalUId": null,
"ReminderMinutesBeforeStart": null,
"IsReminderOn": null,
"HasAttachments": null,
"Subject": "Bi-Annual Event",
"Body": {
"ContentType": 0,
"Content": "Trying to make a bi-annual event",
"AdditionalData": null,
"ODataType": "microsoft.graph.itemBody"
},
"BodyPreview": null,
"Importance": null,
"Sensitivity": null,
"Start": {
"DateTime": "2020-05-04T16:00:00",
"TimeZone": "Central Standard Time",
"AdditionalData": null,
"ODataType": "microsoft.graph.dateTimeTimeZone"
},
"OriginalStart": null,
"End": {
"DateTime": "2020-05-04T17:00:00",
"TimeZone": "Central Standard Time",
"AdditionalData": null,
"ODataType": "microsoft.graph.dateTimeTimeZone"
},
"Location": {
"DisplayName": "the office",
"LocationEmailAddress": null,
"Address": null,
"LocationUri": null,
"Coordinates": null,
"LocationType": null,
"UniqueId": null,
"UniqueIdType": null,
"AdditionalData": null,
"ODataType": "microsoft.graph.location"
},
"Locations": null,
"IsAllDay": null,
"IsCancelled": null,
"IsOrganizer": null,
"Recurrence": {
"Pattern": {
"Type": 4,
"Interval": 2,
"Month": 5,
"DayOfMonth": 4,
"DaysOfWeek": null,
"FirstDayOfWeek": null,
"Index": null,
"AdditionalData": null,
"ODataType": "microsoft.graph.recurrencePattern"
},
"Range": {
"Type": 1,
"StartDate": {
"Year": 2020,
"Month": 5,
"Day": 4
},
"EndDate": null,
"RecurrenceTimeZone": null,
"NumberOfOccurrences": null,
"AdditionalData": null,
"ODataType": "microsoft.graph.recurrenceRange"
},
"AdditionalData": null,
"ODataType": "microsoft.graph.patternedRecurrence"
},
"ResponseRequested": null,
"SeriesMasterId": null,
"ShowAs": null,
"Type": null,
"Attendees": [
{
"Status": null,
"Type": 0,
"EmailAddress": {
"Name": null,
"Address": "test.email.123#someTestDomain.org",
"AdditionalData": null,
"ODataType": "microsoft.graph.emailAddress"
},
"AdditionalData": null,
"ODataType": "microsoft.graph.attendee"
}
],
"Organizer": null,
"WebLink": null,
"OnlineMeetingUrl": null,
"IsOnlineMeeting": null,
"OnlineMeetingProvider": null,
"OnlineMeeting": null,
"Attachments": null,
"SingleValueExtendedProperties": null,
"MultiValueExtendedProperties": null,
"Calendar": null,
"Instances": null,
"Extensions": null,
"CreatedDateTime": null,
"LastModifiedDateTime": null,
"ChangeKey": null,
"Categories": null,
"Id": null,
"ODataType": "microsoft.graph.event",
"AdditionalData": null
}
Does your request look different?
Also, I noticed this is only an issue on the desktop client, the events appear normally on the web client

.NET MVC Unable to Deserialize JSON

I am using the results from json2csharp.com on the response below from a GET request within my MVC Model:
{
"Id": 1111111,
"CreateLocation": "xxxxxxxxEZ-V12",
"ConstituentType": {
"Description": "Individual",
"Id": 1,
"Inactive": false,
"ConstituentGroup": {
"Description": "Individual",
"Id": 1,
"Inactive": false
}
},
"DisplayName": "xxxxxxxx xxxxxxxx",
"FirstName": "xxxxxxxx",
"Inactive": {
"Id": 1,
"Description": "Active",
"Inactive": false
},
"InactiveReason": null,
"LastActivityDate": "2016-10-16T02:32:15Z",
"LastName": "xxxxxxxx",
"MailIndicator": {
"Description": "(none)",
"Id": 3,
"Inactive": false
},
"EmarketIndicator": {
"Description": "(none)",
"Id": 3,
"Inactive": false
},
"MiddleName": "",
"NameStatus": {
"Description": " ",
"Id": 1,
"Inactive": false
},
"OriginalSource": {
"Description": "Test Test",
"Id": 4,
"Inactive": false
},
"PhoneIndicator": {
"Description": "(none)",
"Id": 3,
"Inactive": false
},
"Prefix": {
"Description": "",
"Id": -1,
"Inactive": false
},
"Gender": null,
"Suffix": {
"Description": "",
"Id": -1,
"Inactive": false
},
"Salutation": {
"BusinessTitle": null,
"CreatedDateTime": "2016-05-21T16:47:52Z",
"CreateLocation": "xxxxxxxxEZ-V12",
"Constituent": {
"Id": 8775975
},
"CreatedBy": "xxxxxxxx",
"Id": 912925,
"DefaultIndicator": true,
"EnvelopeSalutation1": "xxxxxxxx xxxxxxxx",
"EnvelopeSalutation2": "",
"Label": true,
"UpdatedDateTime": "2016-05-21T16:47:52.937Z",
"UpdatedBy": "xxxxxxxx",
"LetterSalutation": "xxxxxxxx xxxxxxxx",
"SalutationType": {
"Description": "Default",
"Id": 0,
"Inactive": false
},
"EditIndicator": true,
"IsFromAffiliation": false
},
"Address": {
"Id": 9781315,
"AffiliatedConstituent": null,
"AltSalutationType": {
"Description": "Default",
"Id": 0,
"Inactive": false
},
"AddressType": {
"Description": "Home Address",
"Id": 3,
"Inactive": false
},
"City": "Brooklyn",
"CreatedDateTime": "2016-05-21T16:47:52Z",
"CreateLocation": "xxxxxxxxEZ-V12",
"CreatedBy": "xxxxxxxx",
"Constituent": {
"Id": 8775975
},
"DeliveryPoint": "",
"EndDate": null,
"GeoArea": 35,
"Inactive": false,
"Label": true,
"UpdatedDateTime": "2016-09-21T16:00:46.497Z",
"UpdatedBy": "NCOA$STD",
"Months": "YYYYYYYYYYYY",
"NcoaAction": 3,
"NcoaSession": 9,
"PostalCode": "12121212",
"PostalCodeFormatted": "11205-2348",
"PrimaryIndicator": true,
"StartDate": null,
"State": {
"Description": "New York",
"StateCode": "NY",
"Id": 51,
"Inactive": false,
"Country": {
"Description": "USA",
"Id": 1,
"Inactive": false
}
},
"Street1": "11 Fadeaddress Ave",
"Street2": null,
"Street3": null,
"Country": {
"Description": "USA",
"Id": 1,
"Inactive": false
},
"EditIndicator": true,
"IsFromAffiliation": false
},
"ElectronicAddress": {
"Address": "test#test.edu",
"AffiliatedConstituent": null,
"AltSalutationType": null,
"CreatedDateTime": "2016-05-21T16:47:53Z",
"CreateLocation": "xxxxxxxxEZ-V12",
"CreatedBy": "xxxxxxxx",
"Constituent": {
"Id": 8775975
},
"Id": 9781317,
"ElectronicAddressType": {
"Description": "Home Email",
"Id": 1,
"Inactive": false,
"IsEmail": true
},
"EndDate": null,
"AllowHtmlFormat": true,
"Inactive": false,
"UpdatedDateTime": "2016-05-21T16:47:53.03Z",
"UpdatedBy": "xxxxxxxx",
"AllowMarketing": true,
"Months": "YYYYYYYYYYYY",
"PrimaryIndicator": true,
"StartDate": null,
"EditIndicator": true,
"IsFromAffiliation": false,
"IsEmail": true
},
"PrimaryPhoneNumbers": [
{
"Address": {
"Id": 9781315,
"AddressType": {
"Description": "Home Address",
"Id": 3,
"Inactive": false
}
},
"AllowTelemarketing": true,
"DayEveningIndicator": " ",
"Constituent": {
"Id": 8775975
},
"Id": 9781316,
"Inactive": false,
"PhoneNumber": "11111111",
"PhoneFormatted": "(917) 561-0972 ",
"PhoneSearch": "11111111",
"PhoneType": {
"Description": "Phone 1",
"Id": 1,
"Inactive": false
},
"CreatedBy": "xxxxxxxx",
"CreateLocation": "xxxxxxxxEZ-V12",
"CreatedDateTime": "2016-05-21T16:47:53Z",
"UpdatedDateTime": "2016-05-21T16:47:53.027Z",
"UpdatedBy": "xxxxxxxx",
"EditIndicator": true
}
],
"CreatedDateTime": "2015-05-23T14:03:23Z",
"CreatedBy": "xxxxxxxx",
"UpdatedDateTime": "2016-10-16T02:32:15.527Z",
"UpdatedBy": "dbo ",
"SortName": "xxxxxxxx/xxxxxxxx",
"Affiliates": [],
"ProtectionType": null
}
But when I try to deserialize the JSON output and return the results to my View with
//Storing the response details recieved from web api
var json = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
EmpInfo = JsonConvert.DeserializeObject<List<Constituent>>(json);
I get the error Cannot deserialize the current JSON object...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...that can be deserialized from a JSON object.
Your example response is a single object, not an array. I can't see your implementation of Constituent but assume it matches that definition?
In which case you should be able to deserialize the single result (rather than a list) using:
EmpInfo = JsonConvert.DeserializeObject<Constituent>(json);
var result = JsonConvert.DeserializeObject<dynamic>(JSONtext)

Parse JSON containing unnamed node

I have the following JSON payload.
The challenge is to fetch the name value and the corresponding root node number (3925 or 3932) since this node is unnamed.
I am using C#
"3925": {
"totalExecutions": 2,
"endDate": "",
"description": "",
"totalExecuted": 2,
"started": "",
"versionName": "Custom Pipes Development",
"expand": "executionSummaries",
"projectKey": "WUSDV007",
"versionId": 22361,
"environment": "",
"totalCycleExecutions": 2,
"totalDefects": 0,
"build": "",
"createdBy": "mghosh",
"ended": "",
"name": "SetMaxFutureDateFromCustomerField_Mobile",
"totalFolders": 0,
"modifiedBy": "mghosh",
"projectId": 17101,
"createdByDisplay": "Mayukh Ghosh",
"startDate": "",
}
}
"3932": {
"totalExecutions": 2,
"endDate": "",
"description": "",
"totalExecuted": 2,
"started": "",
"versionName": "Custom Pipes Development",
"expand": "executionSummaries",
"projectKey": "WUSDV007",
"versionId": 22361,
"environment": "",
"totalCycleExecutions": 2,
"totalDefects": 0,
"build": "",
"createdBy": "nkonda",
"ended": "",
"name": "WUSDV007-29779-Fee Validation",
"totalFolders": 0,
"modifiedBy": "nkonda",
"projectId": 17101,
"createdByDisplay": "Naveen Kumar Konda",
"startDate": "",
}
Any suggestions are highly appreciated.
Try code as follows:
string jsonString = "{\"3925\": { \"totalExecutions\": 2, \"endDate\": \"\", \"description\": \"\", \"totalExecuted\": 2, \"started\": \"\", \"versionName\": \"Custom Pipes Development\", \"expand\": \"executionSummaries\", \"projectKey\": \"WUSDV007\", \"versionId\": 22361, \"environment\": \"\", \"totalCycleExecutions\": 2, \"totalDefects\": 0, \"build\": \"\", \"createdBy\": \"mghosh\", \"ended\": \"\", \"name\": \"SetMaxFutureDateFromCustomerField_Mobile\", \"totalFolders\": 0, \"modifiedBy\": \"mghosh\", \"projectId\": 17101, \"createdByDisplay\": \"Mayukh Ghosh\", \"startDate\": \"\" }}";
var parameters = JObject.Parse(jsonString);
foreach (var item in parameters.OfType<JProperty>())
{
var innerObject = JObject.Parse(item.Value.ToString());
Console.WriteLine(innerObject.ToString());
}

How should I retrieve just the names and emails of ApplicationUser in .net core API

I'm kinda new so I apologize if I'm not using the correct terminology.
Basically I'm building a .net core web app with an AngularJs component in the frontend to retrieve and display the results from my API's JSON get request.
[Authorize(Roles = "Manager")]
[HttpGet("Clients")]
public async Task<JsonResult> AllClients()
{
IEnumerable<AppUser> Clients = await _userManagerService.GetUsersInRoleAsync("Client");
return Json(listErrorMsg(Clients));
}
The problem i'm having is that the API sends EVERY column of every user, as expected.
[
{
"firstName": "Client2",
"lastName": "2",
"residentialAddress": null,
"residentialSuburb": null,
"residentialPostCode": null,
"residentialCity": null,
"residentialstateTerritory": "NULL",
"postalAddress": null,
"postalSuburb": null,
"postalPostCode": null,
"postalCity": null,
"postalstateTerritory": "NULL",
"lastSync": "0001-01-01T00:00:00",
"accountCreated": "0001-01-01T00:00:00",
"lastVisited": "0001-01-01T00:00:00",
"client": null,
"clientID": null,
"id": "2075c598-5bc3-4f74-a843-ac41e4d0bc36",
"userName": "Client2",
"normalizedUserName": "CLIENT2",
"email": null,
"normalizedEmail": null,
"emailConfirmed": true,
"passwordHash": "AQAAAAEAACcQAAAAELFKxfP2giuEtg8+M4q7Pu2+lpGBDOwWkajL/KnKTGQ5gkBnYdZZ/tdtpNnQyyRjpA==",
"securityStamp": "4146b78a-8710-4951-90c9-da17af4e0d95",
"concurrencyStamp": "245bdd70-8d46-4e01-a512-2bb124fac42e",
"phoneNumber": null,
"phoneNumberConfirmed": false,
"twoFactorEnabled": false,
"lockoutEnd": null,
"lockoutEnabled": true,
"accessFailedCount": 0,
"roles": [],
"claims": [],
"logins": []
},
{
"firstName": "Client1",
"lastName": "1",
"residentialAddress": null,
"residentialSuburb": null,
"residentialPostCode": null,
"residentialCity": null,
"residentialstateTerritory": "NULL",
"postalAddress": null,
"postalSuburb": null,
"postalPostCode": null,
"postalCity": null,
"postalstateTerritory": "NULL",
"lastSync": "0001-01-01T00:00:00",
"accountCreated": "0001-01-01T00:00:00",
"lastVisited": "0001-01-01T00:00:00",
"client": null,
"clientID": null,
"id": "3466054a-42b5-4185-a677-4bf110dea420",
"userName": "Client1",
"normalizedUserName": "CLIENT1",
"email": null,
"normalizedEmail": null,
"emailConfirmed": true,
"passwordHash": "AQAAAAEAACcQAAAAELWrulfO5YQudMggGpvXPos54Faie7PxOac1/Yjy9PjY4PuSpb6Kpqfn85a4ABbVyg==",
"securityStamp": "47370050-772b-4365-8238-ebacebeea802",
"concurrencyStamp": "c072bf2e-9d21-4c66-95da-552fa0af50ca",
"phoneNumber": null,
"phoneNumberConfirmed": false,
"twoFactorEnabled": false,
"lockoutEnd": null,
"lockoutEnabled": true,
"accessFailedCount": 0,
"roles": [],
"claims": [],
"logins": []
},
{
"firstName": "Client0",
"lastName": "0",
"residentialAddress": null,
"residentialSuburb": null,
"residentialPostCode": null,
"residentialCity": null,
"residentialstateTerritory": "NULL",
"postalAddress": null,
"postalSuburb": null,
"postalPostCode": null,
"postalCity": null,
"postalstateTerritory": "NULL",
"lastSync": "0001-01-01T00:00:00",
"accountCreated": "0001-01-01T00:00:00",
"lastVisited": "2017-05-09T21:53:42.5080226",
"client": null,
"clientID": null,
"id": "a504e831-9524-480e-b5a0-745891da65b4",
"userName": "Client0",
"normalizedUserName": "CLIENT0",
"email": "fake#fake.com",
"normalizedEmail": "FAKE#FAKE.COM",
"emailConfirmed": true,
"passwordHash": "AQAAAAEAACcQAAAAEOvIdZDsXnYt+ToSYaKXmsnNSrfgwjy/Or4vM4pMo5gx45YFrxiZAig9a4ZEatg9KA==",
"securityStamp": "a4dcce55-660e-4d06-b2ed-ac065b6c0552",
"concurrencyStamp": "0b4759b5-e0a5-4a08-a3af-595360f8e30b",
"phoneNumber": null,
"phoneNumberConfirmed": false,
"twoFactorEnabled": false,
"lockoutEnd": "2017-05-02T01:55:03.7282498+00:00",
"lockoutEnabled": true,
"accessFailedCount": 0,
"roles": [],
"claims": [],
"logins": []
}
]
However, I only want a few of fields to be sent through the API like name and email just to protect user data.
{
"firstName": "Client2",
"lastName": "2",
"id": "2075c598-5bc3-4f74-a843-ac41e4d0bc36",
"userName": "Client2",
"normalizedUserName": "CLIENT2",
"email": null,
"normalizedEmail": null,
"phoneNumber": null,
},
How should I go about this?
How about just selecting the values from the list as an anonymous object
return Json(listErrorMsg(Clients.Select(a=> new {
firstName = a.firstName,
lastName = a.lastName,
id = a.id,
userName = a.userName,
normalizedUserName = a.normalizedUserName,
email = a.email,
normalizedEmail = a.normalizedEmail,
phoneNumber = a.phoneNumber
}));

Categories