Resource with specified id or name already exists - Dcoumentdb - c#

I have inserted two json document using documentdb and have them in a list named Hotelwithroomtype.I want to update the created json document with some new values and then recreate them as new document. Here's my code
foreach (var item in Hotelwithroomtype)
{
foreach (var cal in Calendardata)
{
item.CalendarDate = Convert.ToDateTime(cal.CalendarDate);
item.CalendarDay = cal.Calendarday;
item.issweekday = Convert.ToBoolean(cal.isweekday);
item.issweekend = Convert.ToBoolean(cal.isweekend);
foreach (var prop in item.RoomTypes.RoomTypeList)
{
prop.Mon = "0";
prop.Tue = "0";
prop.Wed = "0";
prop.Thur = "0";
prop.Fri = "0";
prop.Sat = "0";
prop.Sun = "0";
prop.Count = "0";
prop.CountType = "0";
}
// var docExists = client.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri("next", "nextCollection"))
//.Where(doc => doc.Id == item.id)
//.Select(doc => doc.Id)
//.AsEnumerable()
//.Any();
await client.CreateDocumentAsync(collectionLink, item);
}
}
sample Json document which i inserted
{
"HotelCriteria": {
"HotelCode": "101920",
"HotelName": "TestThe Zuri"
},
"RoomTypes": {
"RoomTypeList": [
{
"InvTypeCode": "ZCR",
"Name": "Zuri Club Room",
"BaseOccupancy": 2,
"MaxOccupancy": 3,
"Quantity": 66,
"IsRoomActive": 1,
"RoomDescription": "",
"Availability": 0,
"Mon": "0",
"Tue": "0",
"Wed": "0",
"Thur": "0",
"Fri": "0",
"Sat": "0",
"Sun": "0",
"CountType": "0",
"Count": "0"
},
{
"InvTypeCode": "ZRR",
"Name": "Zuri Room",
"BaseOccupancy": 2,
"MaxOccupancy": 3,
"Quantity": 90,
"IsRoomActive": 1,
"RoomDescription": "",
"Availability": 0,
"Mon": "0",
"Tue": "0",
"Wed": "0",
"Thur": "0",
"Fri": "0",
"Sat": "0",
"Sun": "0",
"CountType": "0",
"Count": "0"
},
{
"InvTypeCode": "ZSR",
"Name": "Zuri Suite Room",
"BaseOccupancy": 2,
"MaxOccupancy": 3,
"Quantity": 4,
"IsRoomActive": 1,
"RoomDescription": "",
"Availability": 0,
"Mon": "0",
"Tue": "0",
"Wed": "0",
"Thur": "0",
"Fri": "0",
"Sat": "0",
"Sun": "0",
"CountType": "0",
"Count": "0"
}
]
},
"RatePlans": {
"RatePlanList": [
{
"RatePlanCode": "B2C00001",
"RatePlanCategory": "B2C",
"RatePlanStatusType": 1,
"RatePlanName": "Channel Rates",
"Description": "Channel Rates",
"InvTypeCode": "ZCR",
"MealPlanCode": "CP",
"MealPlanDesc": "Continental Plan",
"Start": "2016-06-27",
"End": "2017-03-31",
"CurrencyCode": "INR"
},
{
"RatePlanCode": "B2C00001",
"RatePlanCategory": "B2C",
"RatePlanStatusType": 1,
"RatePlanName": "Channel Rates",
"Description": "Channel Rates",
"InvTypeCode": "ZRR",
"MealPlanCode": "CP",
"MealPlanDesc": "Continental Plan",
"Start": "2016-06-27",
"End": "2017-03-31",
"CurrencyCode": "INR"
},
{
"RatePlanCode": "B2C00001",
"RatePlanCategory": "B2C",
"RatePlanStatusType": 1,
"RatePlanName": "Channel Rates",
"Description": "Channel Rates",
"InvTypeCode": "ZSR",
"MealPlanCode": "CP",
"MealPlanDesc": "Continental Plan",
"Start": "2016-06-27",
"End": "2017-03-31",
"CurrencyCode": "INR"
}
]
},
"Inclusions": {
"InclusionList": [
{
"MealPlanCode": "CP",
"MealPlanDesc": "Continental Plan"
}
]
},
"id": "8f236805-d3a5-498b-9cc3-efa7448faa63",
"_rid": "SVcZALakfQAEAAAAAAAAAA==",
"_self": "dbs/SVcZAA==/colls/SVcZALakfQA=/docs/SVcZALakfQAEAAAAAAAAAA==/",
"_etag": "\"00004b09-0000-0000-0000-594a02e80000\"",
"_attachments": "attachments/",
"_ts": 1498022618
}
I want the current document with updated values but need them as a new document.When i tried to create i get the following error "Resource with specified id or name already exists".Any help would be really appreciated.
Thanks

You are trying to instead a new document with id equal to id of the existing document. This is not allowed, so operation fails. Before you insert the modified copy, you need to assign a new id to it.

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

Linq - Ordering Json Products by Price Double

i Have this the products table:
P_Id P_Title P_JsonData P_SC_Id
168 fdsfdf SomeJson 1
SomeJson equals:
{
"pType": "1",
"pTitle": "son 1",
"pProds": [{
"formM": 1,
"sDesc": "<p>son 1</p>",
"lDesc": "<p>son 1<br></p>",
"pColor": "",
"pSize": "XXS",
"postage": "22",
"quatity": 23,
"aPrice": "23",
"rPrice": "23",
"Discounted": "23",
"Price": "23",
"p_Num": "71770005f28641118a617ba8ec070a44",
"images": [{
"mN": 1,
"idImage": "image1",
"fileName": "1724d443fe514050903176247d379e09.jpg",
"bytes": "/img/ProdImages/71770005f28641118a617ba8ec070a44/1724d443fe514050903176247d379e09.jpg"
}, {
"mN": 1,
"idImage": "image2",
"fileName": "f70d2e941fd740c5bd72cb451c04b81b.jpg",
"bytes": "/img/ProdImages/71770005f28641118a617ba8ec070a44/f70d2e941fd740c5bd72cb451c04b81b.jpg"
}, {
"mN": 1,
"idImage": "image3",
"fileName": "4c58e7b0406b48c89fcd5fabe151205a.jpg",
"bytes": "/img/ProdImages/71770005f28641118a617ba8ec070a44/4c58e7b0406b48c89fcd5fabe151205a.jpg"
}]
}, {
"formM": 2,
"sDesc": "<p>son 2</p>",
"lDesc": "<p>son 2<br></p>",
"pColor": "",
"pSize": "XXS",
"postage": "3",
"quatity": 3,
"aPrice": "3",
"rPrice": "3",
"Discounted": "3",
"Price": "3",
"p_Num": "7be125c9df94481a84bf1eff928fc2a3",
"images": [{
"mN": 2,
"idImage": "image1",
"fileName": "c117460b70194788b162d5445f01e151.jpg",
"bytes": "/img/ProdImages/7be125c9df94481a84bf1eff928fc2a3/c117460b70194788b162d5445f01e151.jpg"
}, {
"mN": 2,
"idImage": "image2",
"fileName": "5a70893f7e5a401398344d4269f245ce.jpg",
"bytes": "/img/ProdImages/7be125c9df94481a84bf1eff928fc2a3/5a70893f7e5a401398344d4269f245ce.jpg"
}]
}, {
"formM": 0,
"sDesc": "",
"lDesc": "",
"pColor": "",
"pSize": "0",
"postage": "0",
"quatity": 0,
"aPrice": "0",
"rPrice": "0",
"Discounted": "0",
"Price": "0",
"p_Num": "1b7752c65d3747ed99562745b875b8da",
"images": []
}, {
"formM": 0,
"sDesc": "",
"lDesc": "",
"pColor": "",
"pSize": "0",
"postage": "0",
"quatity": 0,
"aPrice": "0",
"rPrice": "0",
"Discounted": "0",
"Price": "0",
"p_Num": "5b817d94b3ec4471a26a0a47a15cc37c",
"images": []
}]
}
This SomeJson Represents the products for each row in the product table so a product can have many products if two products are the same but is differentiated by size and colour so they would have different prices but fit in with the same product.
Now each row in the products table will have this SomeJson, what i need to do is order the json by price so i get the lowest value in element 0 of the SomeJson.
And i want to order by price descending so i get the highest price from the SomeJson at element 0.
I tried this:
Lowest to Highest Price
data = data.OrderBy(x => JsonConvert.DeserializeObject<MainProduct>(x.P_JsonData).pProds.Where(g => Convert.ToDouble(g.Price) > 0 && g.formM > 0).OrderBy(d => Convert.ToDouble(d.Price)).ElementAt(0).Price).ToList();
Highest to Lowest Price:
data = data.OrderByDescending(x => JsonConvert.DeserializeObject<MainProduct>(x.P_JsonData).pProds.Where(g => Convert.ToDouble(g.Price) > 0 && g.formM > 0).OrderByDescending(d => d.Price).ElementAt(0).Price).ToList();
But no luck
Here are the Objects that make up this product table and json:
public class MainProduct
{
public string pType;
public string pTitle;
public List<ProductJson> pProds;
}
public class ProductJson
{
public int formM;
public string sDesc;
public string lDesc;
public string pColor;
public string pSize;
public string postage;
public int quatity;
public string aPrice;
public string rPrice;
public string Discounted;
public string Price;
public string p_Num;
public List<ImageJson> images;
}
public class ImageJson
{
public int mN;
public string idImage;
public string fileName;
public string bytes;
}
So how would i achieve getting the lowest to high and highest to lowest?
You can easily get the max price value using Json.Linq without deserializing JSON to object model
var json = JObject.Parse(jsonString);
var maxValue = json["pProds"].Max(token => token["Price"]?.Value<double>());
Then you can put it into OrderBy statement

How do I get UNIQUE categories from all documents in CosmosDB?

I have millions of documents in CosmosDB using SQL API, and I need to find the unique categories from all documents.
The documents looks like follows, you can see the categories array just under the description, I dont care in what order they are I just need to know all the unique ones from all documents in the collection, I need this so that later on I can create queries on the categories but thats a later question I first need to get them all out so I know what all the possible options are, but I am unable to figure out the query to do this so that I get only the category names.
{
"id": "56d934d3-90bf-4f5a-b602-e515fefa599f",
"_id": "5bf6705f9568cf00013cd13c",
"vendor": "XXX",
"updatedAt": "2018-11-23T03:55:30.044Z",
"locales": [
{
"title": "Cold shoulder t-shirt",
"description": "Because collar bones. Trending cold shoulder t-shirt in 100% organic cotton. Classic, wide and boxy t-shirt fit with cut-out details. In black, because black tees and fashion are like this (insert friendly hand gesture). This style is online exclusive.",
"categories": [
"Women",
"clothing",
"tops"
],
"brand": null,
"images": [
"https://lp.xxx.com/app002prod?set=source[01_0659881_001_102],type[ECOMLOOK],device[hdpi],quality[80],ImageVersion[2018081]&call=url[file:/product/main]",
"https://lp.xxx.com/app002prod?set=source[01_0659881_001_203],type[ECOMLOOK],device[hdpi],quality[80],ImageVersion[2018081]&call=url[file:/product/main]",
"https://lp.xxx.com/app002prod?set=source[01_0659881_001_301],type[ECOMLOOK],device[hdpi],quality[80],ImageVersion[2018081]&call=url[file:/product/main]",
"https://lp.xxx.com/app002prod?set=source[02_0659881_001_101],type[PRODUCT],device[hdpi],quality[80],ImageVersion[1.0]&call=url[file:/product/main]"
],
"country": "SE",
"currency": "SEK",
"language": "en",
"variants": [
{
"artno": "0659881001",
"urls": [
"https://click.linksynergy.com/link?id=INtcw3sexSw&offerid=491018&type=2&murl=https%3A%2F%2Fwww.xxx.com%2Fen_sek%2Fclothing%2Ftops%2Fproduct.cold-shoulder-t-shirt-black-magic.0659881001.html"
],
"price": 80,
"stock": 0,
"attributes": {
"size": "XXS",
"color": "Black magic"
}
},
{
"artno": "xxx",
"urls": [
"https://click.linksynergy.com/link?id=INtcw3sexSw&offerid=491018&type=2&murl=https%3A%2F%2Fwww.xxx.com%2Fen_sek%2Fclothing%2Ftops%2Fproduct.cold-shoulder-t-shirt-black-magic.0659881001.html"
],
"price": 80,
"stock": 0,
"attributes": {
"size": "XS",
"color": "Black magic"
}
},
{
"artno": "0659881001",
"urls": [
"https://click.linksynergy.com/link?id=INtcw3sexSw&offerid=491018&type=2&murl=https%3A%2F%2Fwww.xxx.com%2Fen_sek%2Fclothing%2Ftops%2Fproduct.cold-shoulder-t-shirt-black-magic.0659881001.html"
],
"price": 80,
"stock": 0,
"attributes": {
"size": "XL",
"color": "Black magic"
}
},
{
"artno": "0659881001",
"urls": [
"https://click.linksynergy.com/link?id=INtcw3sexSw&offerid=491018&type=2&murl=https%3A%2F%2Fwww.xxx.com%2Fen_sek%2Fclothing%2Ftops%2Fproduct.cold-shoulder-t-shirt-black-magic.0659881001.html"
],
"price": 80,
"stock": 0,
"attributes": {
"size": "S",
"color": "Black magic"
}
},
{
"artno": "0659881001",
"urls": [
"https://click.linksynergy.com/link?id=INtcw3sexSw&offerid=491018&type=2&murl=https%3A%2F%2Fwww.xxx.com%2Fen_sek%2Fclothing%2Ftops%2Fproduct.cold-shoulder-t-shirt-black-magic.0659881001.html"
],
"price": 80,
"stock": 1,
"attributes": {
"size": "M",
"color": "Black magic"
}
},
{
"artno": "0659881001",
"urls": [
"https://click.linksynergy.com/link?id=INtcw3sexSw&offerid=491018&type=2&murl=https%3A%2F%2Fwww.xxx.com%2Fen_sek%2Fclothing%2Ftops%2Fproduct.cold-shoulder-t-shirt-black-magic.0659881001.html"
],
"price": 80,
"stock": 0,
"attributes": {
"size": "L",
"color": "Black magic"
}
}
]
}
],
"_rid": "QEwcALNbIz8GAAAAAAAAAA==",
"_self": "dbs/QEwcAA==/colls/QEwcALNbIz8=/docs/QEwcALNbIz8GAAAAAAAAAA==/",
"_etag": "\"6a0003c6-0000-0000-0000-5bf7958c0000\"",
"_attachments": "attachments/",
"_ts": 1542952332
}
Please see my test, it could get all the unique categories names.
Sample document:
[
{
"id": "1",
"locales": [
{
"categories": [
"Women",
"clothing",
"tops"
]
}
]
},
{
"id": "2",
"locales": [
{
"categories": [
"Men",
"test",
"tops"
]
}
]
}
]
SQL:
SELECT distinct cat FROM c
join l in c.locales
join cat in l.categories
Output:
[
{
"cat": "Women"
},
{
"cat": "clothing"
},
{
"cat": "tops"
},
{
"cat": "Men"
},
{
"cat": "test"
}
]
If you don't want to case sensitive,just use LOWER function in sql.
SELECT distinct Lower(cat) FROM c
join l in c.locales
join cat in l.categories
If you want to get ["Women","clothing","tops","Men","test"], it can't be parsed as an array in single sql directly, you could use stored procedure to parse the output array.
For example, add below code in stored procedure.
var returnArray = [];
for(var i=0 ;i<array.size;i++){
returnArray.push(array[i].value)
}
return returnArray;

Get Json Array Size

I have Two Json returned from Web API which contain dynamic size array "contacts" and "amenities".
Normally I will access the fixed size array "results" in Json with the following code as I am the on fix the size.
string json = _obj.GetJsonResult(url);
Hotel hotel = Newtonsoft.Json.JsonConvert.DeserializeObject<Hotel>(json);
hotelName = hotel.results[0].property_name;
I have tried the following Link and following code to get the dynamic array size back but it don't seem to be working.
var jObject = JObject.Parse(json);
JArray jArray = (JArray)jObject["hotel.results[0].contacts"];
int length = jArray.Count;
Json One
{
"results": [
{
"property_code": "FGPENOTP",
"property_name": "Olive Tree Penang",
"location": {
"latitude": 5.32708,
"longitude": 100.27944
},
"address": {
"line1": "No 76 Jalan Mahsuri",
"city": "Bayan Lepas",
"postal_code": "11950",
"country": "MY"
},
"total_price": {
"amount": "265.00",
"currency": "MYR"
},
"min_daily_rate": {
"amount": "250.00",
"currency": "MYR"
},
"contacts": [
{
"type": "PHONE",
"detail": "+6046377777"
},
{
"type": "FAX",
"detail": "+6046377788"
}
],
"amenities": [
{
"amenity": "RESTAURANT",
"ota_code": 76,
"description": "Restaurant"
},
{
"amenity": "ELEVATORS",
"ota_code": 33,
"description": "Elevators"
},
{
"amenity": "LAUNDRY_SERVICE",
"ota_code": 58,
"description": "Laundry/Valet service"
},
{
"amenity": "PARKING",
"ota_code": 68,
"description": "Parking"
},
{
"amenity": "ROOM_SERVICE",
"ota_code": 77,
"description": "Room service"
},
{
"amenity": "SAFE_DEPOSIT_BOX",
"ota_code": 78,
"description": "Safe deposit box"
},
{
"amenity": "OUTDOOR_POOL",
"ota_code": 66,
"description": "Outdoor pool"
},
{
"amenity": "BALLROOM",
"ota_code": 191,
"description": "Ballroom"
}
],
"awards": [
{
"provider": "Local Star Rating",
"rating": "4"
}
],
"images": [],
"rooms": [
{
"booking_code": "A1KBAR",
"room_type_code": "A1K",
"rate_plan_code": "BAR",
"total_amount": {
"amount": "265.00",
"currency": "MYR"
},
"rates": [
{
"start_date": "2018-06-15",
"end_date": "2018-06-16",
"currency_code": "MYR",
"price": 250
}
],
"descriptions": [
"BEST AVAILABLE RATE",
"DELUXE ROOM/ KING OR TWIN SIZED BED/ 28 SQM/",
"FREE WI FI"
],
"room_type_info": {
"room_type": "Room with bath - Superior",
"bed_type": "King",
"number_of_beds": "1"
},
"rate_type_code": "BAR"
}
],
"_links": {
"more_rooms_at_this_hotel": {
"href": "https://api.sandbox.amadeus.com/v1.2/hotels/FGPENOTP?apikey=pa3lM5UhJAZ0AJfzlZHcAKdiGVBA90wA&check_in=2018-06-15&check_out=2018-06-16&lang=EN¤cy=MYR&referrer=more_rooms_at_this_hotel"
}
}
}
]
}
Json Two
{
"results": [
{
"property_code": "WWKULAPT",
"property_name": "Sama Sama Hotel Klia",
"location": {
"latitude": 2.75803,
"longitude": 101.7041
},
"address": {
"line1": "Jalan Cta 4b",
"city": "Selangor",
"postal_code": "64000",
"country": "MY"
},
"total_price": {
"amount": "625.00",
"currency": "MYR"
},
"min_daily_rate": {
"amount": "625.00",
"currency": "MYR"
},
"contacts": [
{
"type": "PHONE",
"detail": "60-3-87873333"
},
{
"type": "FAX",
"detail": "60-3-87875555"
},
{
"type": "EMAIL",
"detail": "info#samasamahotels.com"
},
{
"type": "URL",
"detail": "www.samasamahotels.com"
}
],
"amenities": [
{
"amenity": "COFFEE_SHOP",
"ota_code": 20,
"description": "Coffee shop"
},
{
"amenity": "RESTAURANT",
"ota_code": 76,
"description": "Restaurant"
},
{
"amenity": "ACCESSIBLE_FACILITIES",
"ota_code": 47,
"description": "Accessible facilities"
},
{
"amenity": "BEAUTY_SALON",
"ota_code": 107,
"description": "Beauty shop/salon"
},
{
"amenity": "CAR_RENTAL",
"ota_code": 15,
"description": "Car rental desk"
},
{
"amenity": "CHILDREN_WELCOME",
"ota_code": 218,
"description": "Children welcome"
},
{
"amenity": "ELEVATORS",
"ota_code": 33,
"description": "Elevators"
},
{
"amenity": "CURRENCY_EXCHANGE",
"ota_code": 26,
"description": "Currency exchange"
},
{
"amenity": "EXECUTIVE_FLOOR",
"ota_code": 34,
"description": "Executive floor"
},
{
"amenity": "HOTSPOTS",
"ota_code": 221,
"description": "Hotspots"
},
{
"amenity": "INTERNET_PUBLIC_AREAS",
"ota_code": 178,
"description": "Internet access in public areas"
},
{
"amenity": "JACUZZI",
"ota_code": 55,
"description": "Jacuzzi"
},
{
"amenity": "LAUNDRY_SERVICE",
"ota_code": 58,
"description": "Laundry/Valet service"
},
{
"amenity": "MASSAGE_SERVICES",
"ota_code": 61,
"description": "Massage services"
},
{
"amenity": "NON_PORNOGRAPHIC_TV",
"ota_code": 220,
"description": "Hotel does not provide pornographic films/TV"
},
{
"amenity": "PARKING",
"ota_code": 68,
"description": "Parking"
},
{
"amenity": "SAUNA",
"ota_code": 79,
"description": "Sauna"
},
{
"amenity": "SPA",
"ota_code": 84,
"description": "Spa"
},
{
"amenity": "VALET_PARKING",
"ota_code": 97,
"description": "Valet parking "
},
{
"amenity": "",
"ota_code": 46,
"description": "Hairdresser/barber"
},
{
"amenity": "POOL",
"ota_code": 71,
"description": "Pool"
},
{
"amenity": "ROOM_SERVICE",
"ota_code": 77,
"description": "Room service"
},
{
"amenity": "SAFE_DEPOSIT_BOX",
"ota_code": 78,
"description": "Safe deposit box"
}
],
"awards": [
{
"provider": "OHG",
"rating": "Deluxe"
}
],
"images": [],
"rooms": [
{
"booking_code": "DR12ZZZ",
"room_type_code": "D2T",
"rate_plan_code": "PRO",
"total_amount": {
"amount": "625.00",
"currency": "MYR"
},
"rates": [
{
"start_date": "2018-06-15",
"end_date": "2018-06-16",
"currency_code": "MYR",
"price": 625
}
],
"descriptions": [
"Sama Sama Best Available Rate GDS",
"Deluxe Twin/AC/Free WiFi/LCD TV/36SQM/",
"NonSmoking/Work Desk/Safe/Minibar"
],
"room_type_info": {
"room_type": "Room with bath - Minimum",
"bed_type": "Twin",
"number_of_beds": "2"
},
"rate_type_code": "PRO"
}
],
"_links": {
"more_rooms_at_this_hotel": {
"href": "https://api.sandbox.amadeus.com/v1.2/hotels/WWKULAPT?apikey=pa3lM5UhJAZ0AJfzlZHcAKdiGVBA90wA&check_in=2018-06-15&check_out=2018-06-16&lang=EN¤cy=MYR&referrer=more_rooms_at_this_hotel"
}
}
}
]
}
Thanks for every members here who helped.
Since you are already deserializing your JSON, all you should have to do is call hotel.results[0].contacts.Count.
This will return an integer representing the amount of items in the contacts list.
If contacts is of the array datatype, you will need to use length instead of count.

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)

Categories

Resources