Related
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?
I need to return a success status and message when return data in case of success and error type error message if there is error or no data found .
This is controller code :
public HttpResponseMessage GetPatResult(int Patid,int branchid)
{
using (DBEntities1 entities = new DBEntities1())
{
var entity = entities.LAB_RESULTS_CLINIC_VIEW.Where(e => e.Patient_No == Patid && e.branchid==branchid).ToList();
if (!entity.Any())
{
return Request.CreateResponse(HttpStatusCode.NotFound, "No Results Found ");
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
}
}
The output :
[{"order_number":2000000013,"Test_Id":46,"Test_Name":"Lymphocytes%","Result_Duration":24,"Culture":2,"Normal":"Yes","Report_Date":"2020-11-15T00:00:00","Result":"26","Notes":null,"Low_Range":"24","High_Range":"44","Panic":"","Text_Range":"","machine_name":"Sysmex XN-330","Customer_No":1,"Customer_Name":"Cash Price List","Patient_No":10,"Patient_Name":"ziad adnan","Clinic_File_No":"","Category":"Adult","AGE":25,"SEX":"Male ","Test_Note":"","UNIT":"%","DEPTID":1,"Collection_Date":"2020-11-15T00:00:00","Receiving_Date":"2020-11-15T00:00:00","Group_Name":"CBC WITH DIFFERENTIAL COUNT","SERIAL":12,"GROUPID":2,"packageid":0,"EXAMINED_BY":"ziad","APPROVED_BY":"ziad","UPDATED_BY":null,"UPDATED_DATE":null,"Comments":"","department_name":"Hematology Unit","branchid":2},
{"order_number":2000000013,"Test_Id":47,"Test_Name":"Neutrophils","Result_Duration":24,"Culture":2,"Normal":"Yes","Report_Date":"2020-11-15T00:00:00","Result":"50","Notes":null,"Low_Range":"35","High_Range":"66","Panic":"","Text_Range":"","machine_name":"Sysmex XN-330","Customer_No":1,"Customer_Name":"Cash Price List","Patient_No":10,"Patient_Name":"ziad adnan","Clinic_File_No":"","Category":"Adult","AGE":25,"SEX":"Male ","Test_Note":"","UNIT":"%","DEPTID":1,"Collection_Date":"2020-11-15T00:00:00","Receiving_Date":"2020-11-15T00:00:00","Group_Name":"CBC WITH DIFFERENTIAL COUNT","SERIAL":11,"GROUPID":2,"packageid":0,"EXAMINED_BY":"ziad","APPROVED_BY":"ziad","UPDATED_BY":null,"UPDATED_DATE":null,"Comments":"","department_name":"Hematology Unit","branchid":2}]
The output which I need as the following :
In case of success return "success": true, "data":[] "message": "Data Found" like this example:
{
"success": true,
"data": [
{
"order_number": 2000000013,
"Test_Id": 46,
"Test_Name": "Lymphocytes%",
"Result_Duration": 24,
"Culture": 2,
"Normal": "Yes",
"Report_Date": "2020-11-15T00:00:00",
"Result": "26",
"Notes": null,
"Low_Range": "24",
"High_Range": "44",
"Panic": "",
"Text_Range": "",
"machine_name": "Sysmex XN-330",
"Customer_No": 1,
"Customer_Name": "Cash Price List",
"Patient_No": 10,
"Patient_Name": "ziad adnan",
"Clinic_File_No": "",
"Category": "Adult",
"AGE": 25,
"SEX": "Male ",
"Test_Note": "",
"UNIT": "%",
"DEPTID": 1,
"Collection_Date": "2020-11-15T00:00:00",
"Receiving_Date": "2020-11-15T00:00:00",
"Group_Name": "CBC WITH DIFFERENTIAL COUNT",
"SERIAL": 12,
"GROUPID": 2,
"packageid": 0,
"EXAMINED_BY": "ziad",
"APPROVED_BY": "ziad",
"UPDATED_BY": null,
"UPDATED_DATE": null,
"Comments": "",
"department_name": "Hematology Unit",
"branchid": 2
},
{
"order_number": 2000000007,
"Test_Id": 1117,
"Test_Name": "ZINC",
"Result_Duration": 24,
"Culture": 2,
"Normal": "Yes",
"Report_Date": "2020-11-08T00:00:00",
"Result": "80",
"Notes": null,
"Low_Range": "60",
"High_Range": "130",
"Panic": "",
"Text_Range": "",
"machine_name": "Access 2",
"Customer_No": 1,
"Customer_Name": "Cash Price List",
"Patient_No": 10,
"Patient_Name": "ziad adnan",
"Clinic_File_No": "",
"Category": "Adult",
"AGE": 25,
"SEX": "Male ",
"Test_Note": "",
"UNIT": "ug/dl",
"DEPTID": 2,
"Collection_Date": "2020-11-07T00:00:00",
"Receiving_Date": "2020-11-07T00:00:00",
"Group_Name": null,
"SERIAL": 1,
"GROUPID": 0,
"packageid": 6329,
"EXAMINED_BY": "ziad",
"APPROVED_BY": "ziad",
"UPDATED_BY": null,
"UPDATED_DATE": null,
"Comments": "",
"department_name": "Clinical Chemistry Unit",
"branchid": 2
}
],
"message": "Data Found "
}
In case no data found or error return :
{
"success": False,
"error": [ "error code and type"],
"message": "error message"
}
How can I do that please and thank you .
Define a result model like this:
public class PatResult
{
public bool Success { get; set; }
public string Message { get; set; }
public List<Entity> Entities { get; set; }
}
Then in the controller depending on the result f. e.
PatResult patResult = new PatResult
{
Success = true,
Message = "Data Found",
Entities = entities
};
return Request.CreateResponse(HttpStatusCode.OK, patResult);
enter image description here [
{
"id": 2532,
"parent_id": 0,
"number": "2532",
"order_key": "wc_order_FgqugoSiTCm8C",
"created_via": "checkout",
"version": "3.8.1",
"status": "completed",
"currency": "SGD",
"date_created": "2020-05-22T07:03:19",
"date_created_gmt": "2020-05-22T07:03:19",
"date_modified": "2020-05-22T07:06:40",
"date_modified_gmt": "2020-05-22T07:06:40",
"discount_total": "0.00",
"discount_tax": "0.00",
"shipping_total": "42.00",
"shipping_tax": "0.00",
"cart_tax": "0.00",
"total": "47.50",
"total_tax": "0.00",
"prices_include_tax": false,
"customer_id": 1,
"customer_ip_address": "157.46.19.210",
"customer_user_agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
"customer_note": "",
"billing": {
"first_name": "Sala",
"last_name": "Printer Test",
"company": "",
"address_1": "sdfgsdf",
"address_2": "",
"city": "",
"state": "",
"postcode": "476456",
"country": "SG",
"email": "ecommerce#unipro.com.sg",
"phone": "5674645"
},
"shipping": {
"first_name": "Sala",
"last_name": "Printer Test",
"company": "",
"address_1": "sdfgsdf",
"address_2": "",
"city": "",
"state": "",
"postcode": "476456",
"country": "SG"
},
"payment_method": "cod",
"payment_method_title": "Cash on delivery",
"transaction_id": "",
"date_paid": "2020-05-22T07:06:40",
"date_paid_gmt": "2020-05-22T07:06:40",
"date_completed": "2020-05-22T07:06:40",
"date_completed_gmt": "2020-05-22T07:06:40",
"cart_hash": "4ebf26dee924ed591c6160c0f21d7fe4",
"meta_data": [
{
"id": 42356,
"key": "is_vat_exempt",
"value": "no"
}
],
"line_items": [
{
"id": 17,
"name": "COCONUT OIL KERAL",
"product_id": 2511,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "4.50",
"subtotal_tax": "0.00",
"total": "4.50",
"total_tax": "0.00",
"taxes": [],
"meta_data": [],
"sku": "106096",
"price": 4.5
},
{
"id": 18,
"name": "STAR",
"product_id": 2512,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "1.00",
"subtotal_tax": "0.00",
"total": "1.00",
"total_tax": "0.00",
"taxes": [],
"meta_data": [],
"sku": "106081",
"price": 1
}
],
"tax_lines": [],
"shipping_lines": [
{
"id": 19,
"method_title": "Flat rate",
"method_id": "flat_rate",
"instance_id": "20",
"total": "42.00",
"total_tax": "0.00",
"taxes": [],
"meta_data": [
{
"id": 155,
"key": "Items",
"value": "COCONUT OIL KERAL × 1, STAR × 1"
}
]
}
],
"fee_lines": [],
"coupon_lines": [],
"refunds": [],
"currency_symbol": "$",
"_links": {
"self": [
{
"href": "https://uniprogroups.com/collegecollection/wp-json/wc/v2/orders/2532"
}
],
"collection": [
{
"href": "https://uniprogroups.com/collegecollection/wp-json/wc/v2/orders"
}
],
"customer": [
{
"href": "https://uniprogroups.com/collegecollection/wp-json/wc/v2/customers/1"
}
]
}
},
{
"id": 2527,
"parent_id": 0,
"number": "2527",
"order_key": "wc_order_ru3ymWKbxuaib",
"created_via": "checkout",
"version": "3.8.1",
"status": "processing",
"currency": "SGD",
"date_created": "2020-05-22T04:32:25",
"date_created_gmt": "2020-05-22T04:32:25",
"date_modified": "2020-05-22T04:32:25",
"date_modified_gmt": "2020-05-22T04:32:25",
"discount_total": "0.00",
"discount_tax": "0.00",
"shipping_total": "42.00",
"shipping_tax": "0.00",
"cart_tax": "0.00",
"total": "44.50",
"total_tax": "0.00",
"prices_include_tax": false,
"customer_id": 1,
"customer_ip_address": "157.46.19.210",
"customer_user_agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
"customer_note": "",
"billing": {
"first_name": "Sala",
"last_name": "Printer Test",
"company": "",
"address_1": "sdfgsdf",
"address_2": "",
"city": "",
"state": "",
"postcode": "476456",
"country": "SG",
"email": "ecommerce#unipro.com.sg",
"phone": "5674645"
},
"shipping": {
"first_name": "Sala",
"last_name": "Printer Test",
"company": "",
"address_1": "sdfgsdf",
"address_2": "",
"city": "",
"state": "",
"postcode": "476456",
"country": "SG"
},
"payment_method": "cod",
"payment_method_title": "Cash on delivery",
"transaction_id": "",
"date_paid": null,
"date_paid_gmt": null,
"date_completed": null,
"date_completed_gmt": null,
"cart_hash": "932d91bdbf989a4c8c3ea868474dfed8",
"meta_data": [
{
"id": 42316,
"key": "is_vat_exempt",
"value": "no"
}
],
"line_items": [
{
"id": 14,
"name": "AMBI 1100",
"product_id": 2514,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "0.00",
"subtotal_tax": "0.00",
"total": "0.00",
"total_tax": "0.00",
"taxes": [],
"meta_data": [],
"sku": "106015",
"price": 0
},
{
"id": 15,
"name": "GRB GASOGOLLA",
"product_id": 2515,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "2.50",
"subtotal_tax": "0.00",
"total": "2.50",
"total_tax": "0.00",
"taxes": [],
"meta_data": [],
"sku": "106014",
"price": 2.5
}
],
"tax_lines": [],
"shipping_lines": [
{
"id": 16,
"method_title": "Flat rate",
"method_id": "flat_rate",
"instance_id": "20",
"total": "42.00",
"total_tax": "0.00",
"taxes": [],
"meta_data": [
{
"id": 131,
"key": "Items",
"value": "AMBI 1100 × 1, GRB GASOGOLLA × 1"
}
]
}
],
"fee_lines": [],
"coupon_lines": [],
"refunds": [],
"currency_symbol": "$",
"_links": {
"self": [
{
"href": "https://uniprogroups.com/collegecollection/wp-json/wc/v2/orders/2527"
}
],
"collection": [
{
"href": "https://uniprogroups.com/collegecollection/wp-json/wc/v2/orders"
}
],
"customer": [
{
"href": "https://uniprogroups.com/collegecollection/wp-json/wc/v2/customers/1"
}
]
}
}
]
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type '_Model.orderClass+oderlist' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array.
You're trying to deserialize a list of objects to a single object. Modify your deserialize call, it should look similar to this example
JsonConvert.DeserializeObject<List<Customer>>(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)
I'm currently stuck on JSON deserialization.
Here is two type of JSON, I can receive :
{
"code": 0,
"response": {
"isFollowing": false,
"isFollowedBy": false,
"connections": {
"google": {
"url": "",
"id": "c35f4e",
"name": "jean"
},
"facebook": {
"url": "https://www.facebook.com/",
"id": "1000064139",
"name": "jean mic"
}
},
"isPrimary": true,
"id": "780",
"location": "",
"isPrivate": false,
"joinedAt": "2013-10-18T16:04:09",
"username": "jeandavid",
"numLikesReceived": 0,
"about": "",
"name": "jean",
"url": "",
"profileUrl": "",
"reputation": ,
"avatar": {
"small": {
"permalink": "https://picture.jpg",
"cache": "https://picture.jpg"
},
"isCustom": false,
"permalink": "https://picture.jpg",
"cache": "/noavatar9.png",
"large": {
"permalink": "w",
"cache": "https://picture.jpg"
}
},
"isAnonymous": false
}
}
And this one :
{
"response": [
{
"uid": 2017156,
"first_name": "David",
"last_name": "Jean",
"sex": 1,
"nickname": "",
"bdate": "12.12.1990",
"photo_medium": "img.jpg"
}
]
}
At beginning, I use :
Dictionary<string, string> deserializedObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
But it works only with unidimensional Json data.
So after looking on Google, I tried to use :
JArray jArr = (JArray)JsonConvert.DeserializeObject(response);
foreach (var item in jArr)
{
Console.WriteLine(item);
}
But I receive this exception :
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'.
For the first JSON data I would like to get the Google and Facebook data and also the username, the reputation, the avatar, the id of the user, ...
Thanks for any help!!