Deserialize a multidimensional Json response - c#

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!!

Related

Filter data from deep json child

the JSON below is taken from other post. My issue is I know the id and I want to find out where is it located. Eg, I got ID 19006 and I want to get Folder2. How am I going to do this.
{
"data": {
"id": 0,
"name": "",
"childFolders": [{
"id": 19002,
"name": "Locker",
"childFolders": [{
"id": 19003,
"name": "Folder1",
"childFolders": [],
"childComponents": [{
"id": 19005,
"name": "route1",
"state": "STOPPED",
"type": "ROUTE"
}]
}, {
"id": 19004,
"name": "Folder2",
"childFolders": [],
"childComponents": [{
"id": 19008,
"name": "comm1",
"state": "STOPPED",
"type": "COMMUNICATION_POINT"
}, {
"id": 19006,
"name": "route2",
"state": "STOPPED",
"type": "ROUTE"
}, {
"id": 19007,
"name": "route3",
"state": "STOPPED",
"type": "ROUTE"
}]
}],
"childComponents": []
}],
"childComponents": []
},
"error": null
}
I write code now it is like this:
var json = GetJsonString();
var model = GetJsonModel(json);
var folderName = GetName(model.data, 19006);
I chekced and code is correct. folderName is Folder2
And the recursive code:
private string GetName(Data data, int searchValue)
{
var folderName = data.name;
foreach (var item in data.childComponents)
{
if (item.id == searchValue)
{
return folderName;
}
}
if (data.childFolders.Length > 0)
{
foreach (var item in data.childFolders)
{
var folderName1 = GetName(item, searchValue);
if (folderName1 != null)
{
return folderName1;
}
}
}
return null;
}
Your model is like this:
EDIT:
I parse Json like this.
return JsonSerializer.Deserialize<YourJson>(test);

Print certain value from a JSON response

Just started playing with C# again and I'm not able to get over this.
I have the following JSON content:
{
"type": "success",
"picks": [
{
"aftermarket": {
"domain": "ao38t8u4h.com",
"fast_transfer": false,
"price": 0,
"status": "notfound",
"type": "",
"username": ""
},
"domain": "ao38t8u4h.com",
"info": "",
"priority": 1,
"status": {
"available": true,
"lookupType": "EPP",
"name": "ao38t8u4h.com",
"premium": false
},
"tld": "com",
"type": "domain"
},
{
"aftermarket": {
"domain": "ao38t8u4h.net",
"fast_transfer": false,
"price": 0,
"status": "notfound",
"type": "",
"username": ""
},
"domain": "ao38t8u4h.net",
"info": "",
"priority": 2,
"status": {
"available": true,
"lookupType": "EPP",
"name": "ao38t8u4h.net",
"premium": false
},
"tld": "net",
"type": "domain"
},
{
"aftermarket": {
"domain": "ao38t8u4h.dev",
"fast_transfer": false,
"price": 0,
"status": "notfound",
"type": "",
"username": ""
},
"domain": "ao38t8u4h.dev",
"info": "",
"priority": 3,
"status": {
"available": true,
"lookupType": "EPP",
"name": "ao38t8u4h.dev",
"premium": false
},
"tld": "dev",
"type": "domain"
},
{
"aftermarket": {
"domain": "ao38t8u4h.ai",
"fast_transfer": false,
"price": 0,
"status": "notfound",
"type": "",
"username": ""
},
"domain": "ao38t8u4h.ai",
"info": "",
"priority": 4,
"status": {
"available": true,
"lookupType": "EPP",
"name": "ao38t8u4h.ai",
"premium": false
},
"tld": "ai",
"type": "domain"
},
{
"aftermarket": {
"domain": "ao38t8u4h.org",
"fast_transfer": false,
"price": 0,
"status": "notfound",
"type": "",
"username": ""
},
"domain": "ao38t8u4h.org",
"info": "",
"priority": 5,
"status": {
"available": true,
"lookupType": "EPP",
"name": "ao38t8u4h.org",
"premium": false
},
"tld": "org",
"type": "domain"
}
]
}
What I'd like to do is obtain the value in ["picks"][0]["status"]["premium"]. What I'd do in Python would be to get the response and then simply print(var["picks"][0]["status"]["premium"]) to print the value; however, I don't know how to accomplish this in C#.
The code I'm using is the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using Newtonsoft.Json;
namespace testing
{
class Program
{
private static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
try
{
string domain = "ao38t8u4h";
string url = "https://rtb.namecheapapi.com/api/picks/" + domain;
string responseBody = await client.GetStringAsync(url);
var json = JsonConvert.DeserializeObject(responseBody);
Console.WriteLine(json);
Console.ReadLine();
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
Console.ReadLine();
}
}
}
}
Json.Net supports the syntax you are used to if you use JTokens.
JToken jt = JToken.Parse(responseBody);
Console.WriteLine(jt["picks"][0]["status"]["premium"]);
Fiddle: https://dotnetfiddle.net/BssMHq
In addition to #mjwills:
Deserialize json. Then print value like so:
Console.WriteLine($"Value = {json.Picks[0].Status.Premium}");

Is there a way to sum the values directly in C# without hitting cosmosDB and run a query?

I am trying to find a way to sum the prices held in an array, the way I am doing it now is to save the document to CosmosDB then run an additional sum(foo) query on it but I am thinking there must be a way so simply do that directly before I save the document to CosmosDB to save the extra round trip to the DocumentDB.
Example Document below.
The values I want to summarise are under:
ApiInputObject.TransactionDetails.Items.Price and there can of course be many items in the array.
I can only figure out how to get a single value out but that seems very inefficient.
{
"InternalTransactionlId": "XXX",
"DocumentType": "order",
"ExternalTransactionId": "externalIdTest2",
"OrderBotResponse": {
"id": "XXX",
"status": "pending",
"checkoutUrl": "https://www.example.com",
"items": [
{
"attributes": {
"color": "Midnight blue",
"size": "L"
},
"price": "500",
"quantity": "1",
"shipping": "0.0",
"title": "ACME Title",
"url": "https://example.com",
"product_id": "XXX",
"imageUrl": "https://example.com/image.jpg",
"status": "pending",
"shippingMethod": "default",
"totalPrice": 500
}
],
"reference": "XXX",
"currency": "SEK",
"country": "SE",
"language": "sv-se",
"provider": "acme",
"callback": {
"refund": "http://example.com",
"success": "http://example.com"
},
"shippingAddress": {},
"logs": [
{
"t": "2019-08-24T20:58:04.844+08:00",
"m": "Created"
}
],
"meta": {
"error": 0
}
},
"ApiInputObject": {
"ApiKey": "XXX",
"OrderType": "directTransaction",
"SourceSystem": {
"SourceSystemName": "ACME"
},
"SourceSystemCountry": "SE",
"DestinationSystem": {
"DestinationSystemName": "acme.com"
},
"DestinationSystemCountry": {
"DestinationSystemCountryName": "SE"
},
"Brand": {
"BrandName": "ACME"
},
"RequestedFeatures": [
"NONE"
],
"ExternalTransactionId": "externalIdTest2",
"TransactionDetails": {
"callback": {
"refund": "http://example.com",
"success": "http://example.com"
},
"items": [
{
"attributes": {
"color": "Midnight blue",
"size": "L"
},
"price": "500",
"quantity": "1",
"shipping": "0.0",
"title": "ACME",
"url": "https://example.com"
}
],
"test": "true",
"reference": "XXX"
}
},
"id": "XXX",
"_rid": "XXX",
"_self": "XXX",
"_etag": "XXX",
"_attachments": "attachments/",
"_ts": 111
}
You can try to use SelectToken to get your JSON data value. then use linq SUM
JObject obj = JObject.Parse(data);
var value = obj.SelectToken("ApiInputObject.TransactionDetails.items").Sum(x=>((int)x["price"]));
c# online

.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)

C# parse JSON access to child object

I have this JSON:
{
"total": 23695,
"total_pages": 1185,
"results": [{
"id": "r7bVvV7MLdQ",
"created_at": "2018-01-17T06:38:03-05:00",
"updated_at": "2018-05-09T03:35:24-04:00",
"width": 4032,
"height": 2526,
"color": "#F7EDE7",
"description": null,
"urls": {
"raw": "https://images.unsplash.com/photo-1516189050082-44d4deb5ceef?ixlib=rb-0.3.5\u0026ixid=eyJhcHBfaWQiOjEyMDd9\u0026s=8b6caac6353f390fbbabde8441dd1959",
"full": "https://images.unsplash.com/photo-1516189050082-44d4deb5ceef?ixlib=rb-0.3.5\u0026q=85\u0026fm=jpg\u0026crop=entropy\u0026cs=srgb\u0026ixid=eyJhcHBfaWQiOjEyMDd9\u0026s=89ca725623d794116d3741907c93ceab",
"regular": "https://images.unsplash.com/photo-1516189050082-44d4deb5ceef?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=entropy\u0026cs=tinysrgb\u0026w=1080\u0026fit=max\u0026ixid=eyJhcHBfaWQiOjEyMDd9\u0026s=666eb6ac25c7fec68d5994545b933726",
"small": "https://images.unsplash.com/photo-1516189050082-44d4deb5ceef?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=entropy\u0026cs=tinysrgb\u0026w=400\u0026fit=max\u0026ixid=eyJhcHBfaWQiOjEyMDd9\u0026s=3dbc611c97d323ff8b4b043cff19317b",
"thumb": "https://images.unsplash.com/photo-1516189050082-44d4deb5ceef?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=entropy\u0026cs=tinysrgb\u0026w=200\u0026fit=max\u0026ixid=eyJhcHBfaWQiOjEyMDd9\u0026s=0c760185c35eadb31a7bba9b9794d424"
},
"links": {
"self": "https://api.unsplash.com/photos/r7bVvV7MLdQ",
"html": "https://unsplash.com/photos/r7bVvV7MLdQ",
"download": "https://unsplash.com/photos/r7bVvV7MLdQ/download",
"download_location": "https://api.unsplash.com/photos/r7bVvV7MLdQ/download"
},
"categories": [],
"sponsored": false,
"likes": 0,
"liked_by_user": false,
"current_user_collections": [],
"slug": "cloud-smoke-steam",
"user": {
"id": "G69mdFHx0X0",
"updated_at": "2018-05-03T14:00:07-04:00",
"username": "maxkuk",
"name": "Max Kukurudziak",
"first_name": "Max",
"last_name": "Kukurudziak",
"twitter_username": null,
"portfolio_url": "http://www.instagram.com/makckuk",
"bio": "Product Designer at MacPaw, Lecturer at Projector",
"location": "Kiev, Ukraine",
"links": {
"self": "https://api.unsplash.com/users/maxkuk",
"html": "https://unsplash.com/#maxkuk",
"photos": "https://api.unsplash.com/users/maxkuk/photos",
"likes": "https://api.unsplash.com/users/maxkuk/likes",
"portfolio": "https://api.unsplash.com/users/maxkuk/portfolio",
"following": "https://api.unsplash.com/users/maxkuk/following",
"followers": "https://api.unsplash.com/users/maxkuk/followers"
},
"profile_image": {
"small": "https://images.unsplash.com/profile-1518780839522-ee199eceaf8c?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=32\u0026w=32\u0026s=c37d2f2844b45f52c0f66cd580a200c8",
"medium": "https://images.unsplash.com/profile-1518780839522-ee199eceaf8c?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=64\u0026w=64\u0026s=93647049c20b6a323870fe0886eee329",
"large": "https://images.unsplash.com/profile-1518780839522-ee199eceaf8c?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=128\u0026w=128\u0026s=aff2d13afe9fe418b562b85c226b7e8e"
},
"instagram_username": "makckuk",
"total_collections": 0,
"total_likes": 6,
"total_photos": 56
},
"tags": [{
"title": "cloud"
},
{
"title": "smoke"
},
{
"title": "steam"
},
{
"title": "mountain"
},
{
"title": "volcano"
},
{
"title": "blue"
},
{
"title": "rock"
},
{
"title": "glacier"
},
{
"title": "field"
},
{
"title": "geysir"
},
{
"title": "iceland"
}],
"photo_tags": [{
"title": "cloud"
},
{
"title": "smoke"
},
{
"title": "steam"
},
{
"title": "mountain"
},
{
"title": "volcano"
},
{
"title": "blue"
},
{
"title": "rock"
},
{
"title": "glacier"
},
{
"title": "field"
},
{
"title": "geysir"
},
{
"title": "iceland"
}]
},
I need to get results.profile_image.small I tried it on many ways but I never figured out how to access to profile_image fields.
Basically I want to do something like this:
dynamic array = JsonConvert.DeserializeObject(responz);
foreach (var itemx in array["results"])
{
MessageBox.Show(itemx.profile_image.small.ToString());
}
I spent last few hours figuring it out, searching searching StackOverflow. The last option is do this with regex which would be very stupid thing to do.
Based on your JSON, the actual path should be:
itemx.user.profile_image.small
So if you modify your code to include the missing "user" portion:
dynamic array = JsonConvert.DeserializeObject(responz);
foreach (var itemx in array["results"])
{
MessageBox.Show(itemx.user.profile_image.small.ToString());
}
That should solve your problem.
However, this problem would likely not have presented itself if you were using a concrete class to deserialize into. You would have type safety and the assistance of Intelisense if you use a concrete class. You can easily convert your JSON sample into a concrete class using Json2CSharp or using the "Paste as Class" function of modern Visual Studio versions.

Categories