Selenium - json - c# - c#

var pre1 = driver.FindElementByTagName("pre").Text.Replace(#"\", "").Trim();
dynamic root = JsonConvert.DeserializeObject(pre1);
I have this JSON response:
{
"success": true,
"message": null,
"outright": false,
"eventId": 0,
"si": 111,
"leonard": [{
"catalog":[0,0,0,0,0,0],
"edit": 25965112,
"mkilo": {
"888;315;2;3;0": {
"id": 1000,
"description": "Car"
},
"888;316;2;4;0": {
"id": 1001,
"description": "Train"
},
"888;317;2;5;0": {
"id": 1002,
"description": "Airplane"
}
},
"ti": "008000",
"checkin": 254,
"searchCar": {
"id": 1000,
"description": "Car"
}
}],
"ti": 149498
}
verified with jsonlint
root.leonard[0].catalog.Count = 6 ---- > OK
but
root.leonard[0].mkilo.Count = null - -- Why?
I want to read the contents of mkilo.

Related

Desearalising JSON with arrays in arrays

I've spent a while trying to work out how to desterilise this JSON file and get each products
ID,NAME,COLLECTION COST, AND WEATHER ITS ON OFFER
Im currently attempting this with Newtonsoft.Json in a C# class.
could someone please point me in the right direction.
Many thanks
for the JSON text visit:
https://pastebin.com/bkQwpsAy
{
"_embedded": {
"products": [{
"uuid": "74f1501f-4a52-490a-b2b9-668f16e2db95",
"createdAt": "2020-04-20T13:44:22.000+00:00",
"itemId": "DRN543",
"altItemGroupId": "",
"popularityScore": 101.22,
"itemName": "Coca-Cola Bottles (GB) 6x1.5L",
"jsonFriendlyItemName": "Coca-Cola Bottles (GB) 6x1.5L",
"seoFriendlyItemName": "coca-cola-bottles-gb-6x1-5l",
"brand": "Coca Cola",
"imageLinks": ["https://jjproducts.global.ssl.fastly.net/jjfoodservice/image/upload/v1588074299/products/DRN543/_S/ggktoxjzbplky4uovec4.jpg"],
"price": 9.99,
"depth": 29.0,
"height": 32.0,
"itemNetWeight": 9.0,
"jadMobileItemName": "Coca Cola (GB) 6x1.5L",
"category1Id": "100005",
"category2Id": "200261",
"category3Id": "300194",
"category4Id": "400084",
"category5Id": "",
"category1Name": "Drinks",
"category2Name": "Soft Drinks",
"category3Name": "Fizzy Drinks",
"category4Name": "Cola",
"category5Name": "",
"origin": "United Kingdom",
"catchOrigin": "",
"productDescription": "",
"sellingPoints": "Coca Cola\nCocaCola",
"shelfLife": 135,
"sizeOrCut": "6x1.5l",
"qtyPerLayer": 20.0,
"standardPalletQty": 80.0,
"unitVolume": 17632.0,
"width": 19.0,
"allergensDeclaration": "",
"storageCondition": "Store cool and dry.",
"storedAt": "2020-11-03T23:52:28.789210Z",
"branches": [{
"locationId": "EN-MW",
"locationName": "Enfield Branch",
"warehouseArea": "DA",
"warehouseZone": "GZ"
}, {
"locationId": "LS-MW",
"locationName": "Leicester Branch",
"warehouseArea": "DA",
"warehouseZone": "GZ"
}
],
"branchesBeforeLastUpdate": [{
"locationId": "EN-MW",
"locationName": "Enfield Branch",
"warehouseArea": "DA",
"warehouseZone": "GZ"
}, {
"locationId": "LS-MW",
"locationName": "Leicester Branch",
"warehouseArea": "DA",
"warehouseZone": "GZ"
}
],
"video": [],
"categoryList": "[{\"id\":\"100005\",\"name\":\"Drinks\"},{\"id\":\"200261\",\"name\":\"Soft Drinks\"},{\"id\":\"300194\",\"name\":\"Fizzy Drinks\"}]",
"categoryId": "100005,200261,300194",
"categoryName": "Drinks,Soft Drinks,Fizzy Drinks",
"categoryNormalised": "[Cola Drinks Fizzy Soft]",
"productFeatures": ["Popular", "Ambient", "Vegan", "Vegetarian"],
"unitSize": "1.5L",
"unitPriceDivider": 0.16666,
"unitPriceTypeDisplayText": "each",
"offer": {
"itemId": "DRN543",
"promoForCc": false,
"promoTagId": "Monthly",
"promoTag": "Monthly Special Promotions",
"promoEnd": "31/12/2020",
"promoDisAmt": 0,
"promoDisPct": 0,
"promoDiscountText": [],
"id": "DRN543"
},
"delivery": {
"price": 8.29,
"priceInc": 8.29,
"unitPriceDisplay": "£1.38 each",
"step": 1.0,
"max": 15.0,
"collection": false
},
"collection": {
"price": 7.29,
"priceInc": 7.29,
"unitPriceDisplay": "£1.21 each",
"step": 1.0,
"max": 15.0,
"collection": true
},
"previouslyPurchased": false,
"favourite": false,
"available": true,
"new": false,
"popular": true,
"popularOnCategory1": true,
"popularOnCategory2": true,
"popularOnCategory3": true,
"ageRestriction": false,
"halal": false,
"vegan": true,
"vegeterian": true,
"numberOfPackage": 6,
"numberOfUnitsInPackage": 1.5,
"unitType": "litre",
"CCMAltItemGroup": "",
"JJeBrand": "Coca Cola",
"JadConsumableDepth": 0.0,
"JadConsumableHeight": 0.0,
"JadConsumableWidth": 0.0,
"JJeCategory1Id": "100005",
"JJeCategory2Id": "200261",
"JJeCategory3Id": "300194",
"JJeCategory4Id": "400084",
"JJeCategory5Id": "",
"JJeCategory1": "Drinks",
"JJeCategory2": "Soft Drinks",
"JJeCategory3": "Fizzy Drinks",
"JJeCategory4": "Cola",
"JJeCategory5": "",
"JJeCookingInstruction": "Best served chilled.",
"JJeIngredients": "Carbonated Water, Sugar, Colour (Caramel E150d), Phosphoric Acid, Natural Flavourings including Caffeine.",
"JadIngredientsHTML": "Carbonated Water, Sugar, Colour (Caramel E150d), Phosphoric Acid, Natural Flavourings including Caffeine.",
"JJeOrigin": "United Kingdom",
"JadCatchOrigin": "",
"JJeProductDescription": "",
"JJeSellingPoints": "Coca Cola\nCocaCola",
"JJeShelfLife": 135,
"JJeSizeOrCut": "6x1.5L",
"JadAllergensDeclaration": "",
"JadStorageCondition": "Store cool and dry.",
"JJeEnergyKJ": 180.0,
"JJeEnergyKCAL": 42.0,
"JJeFatG": "0",
"JadFatSaturatesG": "0",
"JJeCarbohydrateG": "10.6",
"JadCarbohydrateSugarsG": "10.6",
"JJeProteinG": "0",
"JadSodiumG": "0",
"IsAgeRestriction": false,
"IsHalal": false,
"IsVegan": true,
"IsVegeterian": true
}
]
},
"_links": {
"maintenance-message": {
"href": "[]"
},
"announcement-message": {
"href": "[]"
}
},
"page": {
"size": 12,
"totalElements": 18,
"totalPages": 2,
"number": 0
}
}
public static List<JJs.ITEMS> JJSGetProductHTML(String Term)
{
string url = "https://www.website.com/api/product-search-agg/api/v1/product/websearch?b=DG-MW&page=0&q=" + Term+ "&size=12&sortType=search&format=json";
WebClient WC = new WebClient();
string JSON = WC.DownloadString(url);
var onject,= JsonConvert.DeserializeObject<dynamic>(JSON);
string s = onject._embedded.products[0].ToString();
List<JJs.ITEMS> products = new List<JJs.ITEMS>();
foreach (var m in onject._embedded.products)
{
JJs.ITEMS newitem = new JJs.ITEMS();
newitem.Name = m.jsonFriendlyItemName.ToString();
newitem.itemId = m.itemId.ToString();
newitem.price = m.collection.price.ToString();
try
{ m.offer.ToString(); newitem.Promoend = m.offer.promoEnd.ToString(); newitem.Promo = true; }
catch
{ newitem.Promo = false; };
products.Add(newitem);
}
return products;
}
As I didnt want all the feilds, i serialised it then used ".jsonFriendlyItemName",".itemId".. to only get the values I was looking for
thanks #JaromandaX, # Peter B and #dbc for your help

index into Json properly using unity and c#

If I wanted to index into price or galleryId in this json file:
{
"searchId": null,
"listings": [{
"sid": 0,
"id": 25,
"status": 3,
"art": {
"sid": 0,
"artId": 24,
"token": "v",
"name": "A",
"description": "F",
"width": 18.0000,
"height": 24.0000,
"metricWidth": 0.4572,
"metricHeight": 0.6096,
"mediaType": "",
"fullSizeImageUrl": "http",
"thumbnailImageUrl": "http",
"artist": {
"token": null,
"firstName": "V",
"lastName": "G",
"visibleInSearch": false,
"inventoryVisibleInSearch": false
}
},
"galleryId": 1,
"price": 1750,
"listed": "2020-01-18T21:49:41.447"
}]
would this be the correct syntax?
{
for (int i = 0; i < itemData[0]["listings"].Count; i++)
{
database.Add(new Art(itemData[0]["listings"][i]["galleryId"].ToString(),
(int)itemData[0]["listings"][i]["price"]));
#PhilippLenssen you were right, the json was incomplete and not all objects had the field galleryId - this is what broke my code. Thanks for making me look through the entire file!

Generic method to convert a flat JSON array to nested JSON

I have a JSON object as below
[
{
"Id": 7,
"Name": "Colocation Folder",
"ParentId": 1,
"depth": 0
},
{
"Id": 8,
"Name": "CoLo Real Estate",
"ParentId": 7,
"depth": 1
},
{
"Id": 10,
"Name": "CoLo: Burst",
"ParentId": 7,
"depth": 1
},
{
"Id": 34,
"Name": "CoLo Dedicated Bandwidth",
"ParentId": 7,
"depth": 1
},
{
"Id": 10035,
"Name": "Infrastructure as a Service",
"ParentId": 7,
"depth": 1
},
{
"Id": 10037,
"Name": "Software as a Service",
"ParentId": 7,
"depth": 1
},
{
"Id": 10038,
"Name": "IaaS Component Upgrade",
"ParentId": 7,
"depth": 1
},
{
"Id": 668,
"Name": "CoLo Misc Folder",
"ParentId": 7,
"depth": 1
},
{
"Id": 758,
"Name": "CoLo: Conduit Fee",
"ParentId": 668,
"depth": 2
},
{
"Id": 765,
"Name": "CoLo: Private VLAN",
"ParentId": 668,
"depth": 2
}
]
The Id and ParentId fields show the relation between the items. I need to make it as a nested JSON using C#.
Since there will be many such models, I don't want to create individual classes for each model. Is there a generic approach in C# that will take a flat JSON array, take the ID and ParentId fields as input and then return me a nested JSON with all other fields in the array as well? For example, I am looking for an output of nested JSON as below:
[
{
"Id": 7,
"Name": "Colocation Folder",
"items": [
{
"Id": 8,
"Name": "CoLo Real Estate",
"ParentId": 7
},
{
"Id": 10,
"Name": "CoLo: Burst",
"ParentId": 7
},
{
"Id": 34,
"Name": "CoLo Dedicated Bandwidth",
"ParentId": 7
},
{
"Id": 10035,
"Name": "Infrastructure as a Service",
"ParentId": 7
},
{
"Id": 10037,
"Name": "Software as a Service",
"ParentId": 7
},
{
"Id": 10038,
"Name": "IaaS Component Upgrade",
"ParentId": 7
},
{
"Id": 668,
"Name": "CoLo Misc Folder",
"ParentId": 7,
"items": [
{
"Id": 758,
"Name": "CoLo: Conduit Fee",
"ParentId": 668
},
{
"Id": 765,
"Name": "CoLo: Private VLAN",
"ParentId": 668
}
]
}
]
}
]
If you use Json.Net, you can do this conversion in a generic way using the LINQ-to-JSON API (JObjects). The idea is to parse the JSON array and add all the individual items to a dictionary keyed by Id. Then, loop over the dictionary items, and for each one, try to look up the parent. If the parent is found, add the item to the parent's items array (creating it if needed). Otherwise, add the item to the root array. Along the way, remove the depth property from each item, since you don't seem to want that in the output. Lastly, just dump the root array to string to get the final result.
var dict = JArray.Parse(json)
.Children<JObject>()
.ToDictionary(jo => (string)jo["Id"], jo => new JObject(jo));
var root = new JArray();
foreach (JObject obj in dict.Values)
{
JObject parent;
string parentId = (string)obj["ParentId"];
if (parentId != null && dict.TryGetValue(parentId, out parent))
{
JArray items = (JArray)parent["items"];
if (items == null)
{
items = new JArray();
parent.Add("items", items);
}
items.Add(obj);
}
else
{
root.Add(obj);
}
JProperty depth = obj.Property("depth");
if (depth != null) depth.Remove();
}
Console.WriteLine(root.ToString());
Fiddle: https://dotnetfiddle.net/Buza6T
You can use a dynamic object with JSON.Net like so to detect your properties dynamically then you could build a new json object with the desired nesting:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
dynamic d = JArray.Parse(stringy);
foreach(var ob in d)
{
if(ob.ParentID != ob.Id)
{
string debug = "oh snapple, it's a child object";
}
}
Share my working code for you at jsFiddle full source code
recursive function is:
function getNestedChildren(arr, parent) {
var out = []
for(var i in arr) {
if(arr[i].parent == parent) {
var children = getNestedChildren(arr, arr[i].id)
if(children.length) {
arr[i].children = children
}
out.push(arr[i])
}
}
return out
}
full source code:
function getNestedChildren(arr, parent) {
var out = []
for(var i in arr) {
if(arr[i].ParentId == parent) {
var items = getNestedChildren(arr, arr[i].Id)
if(items.length) {
arr[i].items = items
}
out.push(arr[i])
}
}
return out
}
var flat_array = [
{
"Id": 7,
"Name": "Colocation Folder",
"ParentId": 1,
"depth": 0
},
{
"Id": 8,
"Name": "CoLo Real Estate",
"ParentId": 7,
"depth": 1
},
{
"Id": 10,
"Name": "CoLo: Burst",
"ParentId": 7,
"depth": 1
},
{
"Id": 34,
"Name": "CoLo Dedicated Bandwidth",
"ParentId": 7,
"depth": 1
},
{
"Id": 10035,
"Name": "Infrastructure as a Service",
"ParentId": 7,
"depth": 1
},
{
"Id": 10037,
"Name": "Software as a Service",
"ParentId": 7,
"depth": 1
},
{
"Id": 10038,
"Name": "IaaS Component Upgrade",
"ParentId": 7,
"depth": 1
},
{
"Id": 668,
"Name": "CoLo Misc Folder",
"ParentId": 7,
"depth": 1
},
{
"Id": 758,
"Name": "CoLo: Conduit Fee",
"ParentId": 668,
"depth": 2
},
{
"Id": 765,
"Name": "CoLo: Private VLAN",
"ParentId": 668,
"depth": 2
}
]
var nested = getNestedChildren(flat_array, 1)
console.log(nested)

how to JsonConvert.DeserializeObject two data

{
"pagination": {
"next_url": "https://api.instagram.com/v1/users/",
"next_max_id": "98740505131"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"videos": {
"low_bandwidth": {
"url": "https://scontent.cdninstagram.com/t50.2886-16/12787808_180458939000143_910172373_s.mp4",
"width": 480,
"height": 480
},
"standard_resolution": {
"url": "https://scontent.cdninstagram.com/t50.2886-16/12824263_607003579446709_1011139465_n.mp4",
"width": 640,
"height": 640
},
"low_resolution": {
"url": "https://scontent.cdninstagram.com/t50.2886-16/12787808_180458939000143_910172373_s.mp4",
"width": 480,
"height": 480
}
},
"tags": [],
"type": "video",
"location": null,
"comments": {
"count": 2,
"data": [
{
"created_time": 1457332172,
"text": "什麼東西",
"from": {
"username": "d86241",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/11371189_421316874725117_327631552_a.jpg",
"id": 397355082,
"full_name": "Jhao-wei Hvang"
},
"id": 1200511729352353800
},
{
"created_time": 1457771205,
"text": "😀",
"from": {
"username": "realkikog",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/11820496_1860868347487361_262727492_a.jpg",
"id": 530665716,
"full_name": "K I K O"
},
"id": 1204194607797938400
}
]
},
"filter": "Crema",
"created_time": 1457326470,
"link": "https://www.instagram.com/p/BCo546hPKpA/",
"likes": {
"count": 22,
"data": [
{
"username": "ladyyihan",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/10684228_590857344404221_1064502415_a.jpg",
"id": 38863087,
"full_name": "Yihan"
},
{
"username": "miding_cyh",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/10005160_844941595551352_2014300181_a.jpg",
"id": 226855180,
"full_name": "i😸米丁 Juri"
},
{
"username": "aikoyin1985",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12093346_523536977821971_1279823341_a.jpg",
"id": 2228728531,
"full_name": "aiko1985"
},
{
"username": "sh1recheungg",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/927866_1722116411358109_618748252_a.jpg",
"id": 416683725,
"full_name": "Sh1reCheungg"
}
]
},
"images": {
"low_resolution": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s320x320/e15/12446061_1590715141254039_2091776153_n.jpg?ig_cache_key=MTIwMDQ2MzkwMDQ3MDcxNjk5Mg%3D%3D.2",
"width": 320,
"height": 320
},
"thumbnail": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s150x150/e15/12446061_1590715141254039_2091776153_n.jpg?ig_cache_key=MTIwMDQ2MzkwMDQ3MDcxNjk5Mg%3D%3D.2",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/e15/12446061_1590715141254039_2091776153_n.jpg?ig_cache_key=MTIwMDQ2MzkwMDQ3MDcxNjk5Mg%3D%3D.2",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": 1457326470,
"text": "測試東西一下",
"from": {
"username": "jiantai.cai",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/1515128_723721747740304_742397288_a.jpg",
"id": 1417858881,
"full_name": "Mars"
},
"id": 1200463904363030800
},
"user_has_liked": false,
"id": "1200463900470716992_1417858881",
"user": {
"username": "jiantai.cai",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/1515128_723721747740304_742397288_a.jpg",
"id": 1417858881,
"full_name": "Mars"
}
}
]
}
i try
var collection = JsonConvert.DeserializeObject(json);
BUT comments data always get null
like this image
enter image description here
how can i model building this json
i want can
foreach(var item in model){
data.comments.data.text
}
to view
Please help ,
I'm using Newtonsoft 8.0.2 and I was able to get what you are asking with this.
string input = File.ReadAllText("C:\\Public\\input.json");
dynamic collection = JsonConvert.DeserializeObject(input);
foreach (var dataItem in collection.data)
{
dynamic comments = dataItem.comments;
foreach (dynamic comment in comments.data)
{
string text = comment.text;
}
}
What you were missing was that you did not iterate through each comment object under your item.

How to count number of JSON elements in an array in C#

I'm worinkg with instagram API and when I'm receiving recent media with any hashtag by this template:
https://api.instagram.com/v1/tags/{hashtag}/media/recent
I'm receiving data like this:
{
"pagination": {
"next_max_tag_id": "any_number",
"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id": "any_number",
"next_min_id": "any_number",
"min_tag_id": "any_number",
"next_url": "https://api.instagram.com/v1/tags/{hashtag}/media/recent?access_token={my_personal_access-token}"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"any_tag",
"any_tag1",
"any_tag2",
"any_tag3"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Normal",
"created_time": "any_number",
"link": "any_url",
"likes": {
"count": 0,
"data": []
},
"images": {
"low_resolution": {
"url": "any_url",
"width": 320,
"height": 320
},
"thumbnail": {
"url": "any_url",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "any_url",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "any_number",
"text": "any_content",
"from": {
"username": "any_username",
"profile_picture": "any_url",
"id": "any_number",
"full_name": "any_full_name"
},
"id": "any_number"
},
"user_has_liked": false,
"id": "any_number",
"user": {
"username": "any_username",
"profile_picture": "any_url",
"id": "any_number",
"full_name": "any_full_name"
}
},
and so on.
As You can see, object "data" is an Array, and further we can see object "tags", which is also array. how can I check number elements array of array in C#? i tried like this:
JArray items = (JArray)jsonData["data[0].tags"];
int length = items.Count;
but it doesn't work. I parse JSON like this:
dynamic jsonData = JsonConvert.DeserializeObject<dynamic>(JSON_string);
var token = JToken.Parse(str);
var data = token.Value<JArray>("data");
var tags = data[0].Value<JArray>("tags");
var count = tags.Count;
You can also use a JsonPath:
var token = JToken.Parse(str);
var count = token.SelectTokens("$.data[0].tags[*]").Count();

Categories

Resources