I'm using LitJson in a Visual C# Program that I'm creating.
I'm making a while loop like this...
var JsonData = // Parse some sort of json file
var selectedArray = "exampleArray"
while (!JsonData.Keys.Contains(selectedArray))`
{
// show an input box to reassign the selectedArray string
// other wise if the JSON data Contains a key with a name that matches selectedArray. exit the while loop.
}
now I get this error
System.InvalidOperationException occurred
HResult=0x80131509
Message=Instance of JsonData is not a dictionary
Source=LitJson
StackTrace:
at LitJson.JsonData.EnsureDictionary()
at LitJson.JsonData.get_Keys()
at Parser_V1.ParserMain.ParseJSON() in C:\Users\lenovo8.1\documents\visual studio 2017\Projects\Parser V1\Parser V1\Main.cs:line 107
at Parser_V1.ParserMain.ParseJsonMenuItem_Click_1(Object sender, EventArgs e) in C:\Users\lenovo8.1\documents\visual studio 2017\Projects\Parser V1\Parser V1\Main.cs:line 161
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Parser_V1.Program.Main() in C:\Users\lenovo8.1\documents\visual studio 2017\Projects\Parser V1\Parser V1\Program.cs:line 19
the file looks like this...
[
{
"Name": "Scrap Axe",
"Time": 1,
"CraftingArea": "Diy",
"Output": "Wooden Axe",
"Count": 1,
"0,3": "Wood Plank",
"1,3": "Stick",
"1,4": "Wood Plank",
"2,2": "Stick",
"3,1": "Stick"
},
{
"Name": "Scrap Shovel",
"Time": 20,
"CraftingArea": "Diy",
"Output": "Scrap Shovel",
"Count": 1,
"0,4": "Stick",
"1,3": "Stick",
"2,2": "Stick",
"3,0": "Iron Ore",
"3,1": "Iron Ore",
"4,0": "Iron Ore",
"4,1": "Iron Ore"
},
{
"Name": "Scrap Pickaxe",
"Time": 17,
"CraftingArea": "Diy",
"Output": "Scrap Pickaxe",
"Count": 1,
"0,2": "Iron Ore",
"0,3": "Wood Plank",
"0,4": "Crude Nail",
"1,3": "Stick",
"1,4": "Wood Plank",
"2,2": "Stick",
"2,4": "Iron Ore",
"3,1": "Stick"
},
{
"Name": "Metal Pipe",
"Time": 3,
"CraftingArea": "Diy",
"Output": "Metal Pipe",
"Count": 3,
"1,3": "Iron Ore",
"2,2": "Iron Ore",
"3,1": "Iron Ore"
},
{
"Name": "Water Bottle",
"Time": 15,
"CraftingArea": "CookingStation",
"Output": "Water Bottle",
"Count": 1,
"1,2": "Unpurified Water",
"2,1": "Coal Ore",
"2,2": "Coal Ore",
"2,3": "Coal Ore"
},
{
"Name": "Cooked Alien Meat",
"Time": 30,
"CraftingArea": "CookingStation",
"Output": "Cooked Alien Meat",
"Count": 1,
"1,3": "Raw Alien Meat",
"2,3": "Coal Ore",
"2,2": "Water Bottle"
},
{
"Name": "Coal Chunk",
"Time": 3,
"CraftingArea": "CookingStation",
"Output": "Coal Chunk",
"Count": 2,
"1,1": "Coal Ore",
"1,2": "Coal Ore",
"2,1": "Coal Ore",
"2,2": "Coal Ore"
},
{
"Name": "First Aid Bandage",
"Time": 7,
"CraftingArea": "Diy",
"Output": "First Aid Bandage",
"Count": 1,
"1,2": "Cloth",
"2,2": "Cloth"
},
{
"Name": "Iron Pickaxe",
"Time": 90,
"CraftingArea": "Diy",
"Output": "Iron Pickaxe",
"Count": 1,
"0,2": "Iron Ingot",
"0,3": "Iron Ingot",
"1,3": "Stick",
"1,4": "Iron Ingot",
"2,2": "Stick",
"2,4": "Iron Ingot",
"3,1": "Stick"
},
{
"Name": "Steel Pickaxe",
"Time": 90,
"CraftingArea": "Diy",
"Output": "Steel Pickaxe",
"Count": 1,
"0,2": "Steel Ingot",
"0,3": "Steel Ingot",
"1,3": "Stick",
"1,4": "Steel Ingot",
"2,2": "Stick",
"2,4": "Steel Ingot",
"3,1": "Stick"
},
{
"Name": "Wood Planks From Logs",
"Time": 3,
"CraftingArea": "Diy",
"Output": "Wood Plank",
"Count": 4,
"2,2": "Wood Log"
},
{
"Name": "Wood Planks From Sticks",
"Time": 10,
"CraftingArea": "Diy",
"Output": "Wood Plank",
"Count": 1,
"1,2": "Stick",
"2,3": "Stick",
"2,2": "Crude Nail",
"2,1": "Stick",
"3,2": "Stick"
},
{
"Name": "Sticks From Planks",
"Time": 1,
"CraftingArea": "Diy",
"Output": "Stick",
"Count": 4,
"2,2": "Wood Plank",
"3,1": "Wood Plank"
},
{
"Name": "Sticks From Logs",
"Time": 4,
"CraftingArea": "Diy",
"Output": "Stick",
"Count": 8,
"2,2": "Wood Log"
},
{
"Name": "Iron Shovel",
"Time": 45,
"CraftingArea": "Diy",
"Output": "Iron Shovel Planks",
"Count": 4,
"0,4": "Stick",
"1,3": "Stick",
"2,2": "Stick",
"3,0": "Iron Ingot",
"3,1": "Iron Ingot",
"4,0": "Iron Ingot",
"4,1": "Iron Ingot"
},
{
"Name": "Digging Stick",
"Time": 5,
"CraftingArea": "Diy",
"Output": "Digging Stick",
"Count": 1,
"1,3": "Stick",
"2,2": "Stick"
},
{
"Name": "Small Stone From Stone Petals",
"Time": 1,
"CraftingArea": "Diy",
"Output": "Small Stone",
"Count": 1,
"1,1": "Stone Petals",
"1,2": "Stone Petals",
"2,1": "Stone Petals",
"2,2": "Stone Petals"
},
{
"Name": "Steel Ingot",
"Time": 60,
"CraftingArea": "Forge",
"Output": "Steel Ingot",
"Count": 1,
"1,1": "Coal Chunk",
"1,2": "Coal Chunk",
"1,3": "Coal Chunk",
"2,1": "Coal Chunk",
"2,2": "Iron Ingot",
"2,3": "Coal Chunk",
"3,1": "Coal Chunk",
"3,2": "Coal Chunk",
"3,3": "Coal Chunk"
},
{
"Name": "Steel Shovel",
"Category": "Misc",
"Time": 145,
"CraftingArea": "Diy",
"Output": "Steel Shovel",
"Count": 4,
"0,4": "Stick",
"1,3": "Stick",
"2,2": "Stick",
"3,0": "Steel Ingot",
"3,1": "Steel Ingot",
"4,0": "Steel Ingot",
"4,1": "Steel Ingot"
},
{
"Name": "Copper Wire",
"Time": 1,
"CraftingArea": "Diy",
"Output": "Copper Wire",
"Count": 2,
"1,3": "Copper Ingot",
"2,2": "Copper Ingot",
"3,1": "Copper Ingot"
},
{
"Name": "Metal Plate",
"Time": 4,
"CraftingArea": "Forge",
"Output": "Metal Plate",
"Count": 8,
"2,2": "Iron Ingot"
},
{
"Name": "Dirt Wall",
"Time": 1,
"CraftingArea": "Diy",
"Output": "Dirt Wall",
"Count": 1,
"1,1": "Dirt",
"1,2": "Dirt",
"1,3": "Dirt",
"2,1": "Dirt",
"2,2": "Dirt",
"2,3": "Dirt"
},
{
"Name": "Metal Wall",
"Time": 4,
"CraftingArea": "Diy",
"Output": "Metal Wall",
"Count": 1,
"1,1": "Metal Plate",
"1,2": "Metal Plate",
"1,3": "Metal Plate",
"2,1": "Metal Plate",
"2,2": "Metal Plate",
"2,3": "Metal Plate"
},
{
"Name": "Campfire",
"Time": 6,
"CraftingArea": "Diy",
"Output": "Campfire",
"Count": 1,
"2,1": "Stick",
"1,2": "Stick",
"2,3": "Stick",
"3,1": "Small Stone",
"3,2": "Small Stone",
"3,3": "Small Stone"
},
{
"Name": "Builder Tool",
"Time": 1,
"CraftingArea": "Diy",
"Output": "Builder Tool",
"Count": 1,
"2,1": "Stick",
"1,2": "Stick",
"2,2": "Stick",
"1,3": "Stick"
},
{
"Name": "Clay Forge",
"Time": 15,
"CraftingArea": "Diy",
"Output": "Clay Forge",
"Count": 1,
"0,2": "Clay",
"1,1": "Clay",
"1,2": "Wood Log",
"1,3": "Clay",
"2,1": "Clay",
"2,3": "Clay",
"2,2": "Small Stone"
},
{
"Name": "Fueled Generator",
"Time": 32,
"CraftingArea": "Diy",
"Output": "Fueled Generator",
"2,1": "Metal Plate",
"2,2": "Metal Plate",
"2,3": "Metal Plate",
"3,1": "Metal Plate",
"4,1": "Metal Plate",
"4,2": "Metal Plate",
"4,3": "Metal Plate",
"3,3": "Metal Plate",
"0,1": "Copper Ingot",
"0,2": "Copper Wire",
"0,3": "Copper Ingot",
"1,2": "Copper Ingot"
},
{
"Name": "Crude Nail",
"Time": 0,
"CraftingArea": "Diy",
"Output": "Crude Nail",
"2,2": "Iron Ore"
},
{
"Name": "AI Chip",
"Time": 10,
"CraftingArea": "BuildingBench",
"Output": "AI Chip",
"2,1": "Metal Plate",
"2,2": "Metal Plate",
"1,1": "Copper Wire",
"1,2": "Iron Ingot",
"2,3": "Metal Plate"
},
{
"Name": "Light Machinegun Turret",
"Time": 10,
"CraftingArea": "BuildingBench",
"Output": "Light Machinegun Turret",
"1,1": "AI Chip",
"1,3": "Iron Stick",
"1,4": "Iron Stick",
"1,2": "Metal Plate",
"0,2": "Metal Plate",
"0,1": "Copper Ingot",
"0,0": " Copper Wire",
"2,1": "Iron Stick",
"2,3": "Iron Stick",
"3,1": "Iron Stick",
"3,3": "Iron Stick",
"4,1": "Iron Stick",
"4,3": "Iron Stick"
}
]
Is there's a way I can check if the JSON file is a dictionary? since the file above is an array of objects!
I use LitJSON and work in visual studio 2017 community edition.
I do not know LitJSON at all, so I just read the quickstart, which seems to be all that is available.
There is one thing that needs to be clear, what is a dictionary? From what I understand, there is no such thing as a dictionary json file. A dictionary is part of the file, something like:
"name" : "The Dark Side of the Moon",
So in order to read the file, just deserialize it to an object:
JsonData data = JsonMapper.ToObject(json_text);
And then use:
// Dictionaries are accessed like a hash-table
Console.WriteLine("Album's name: {0}", data["album"]["name"]);
I do not know what happens if album/name does not exist, but I expect that it will result in an exception. As you also got an exception because you were using a dictionary method on an object.
One way to validate the file is to just process it. If an exception occurs then it is invalid. This may not be the best way, but it's a way.
The alternative may be to parse the file as described on the quickstart page using a json reader.
public static void PrintJson(string json)
{
JsonReader reader = new JsonReader(json);
Console.WriteLine ("{0,14} {1,10} {2,16}", "Token", "Value", "Type");
Console.WriteLine (new String ('-', 42));
// The Read() method returns false when there's nothing else to read
while (reader.Read()) {
string type = reader.Value != null ?
reader.Value.GetType().ToString() : "";
Console.WriteLine("{0,14} {1,10} {2,16}",
reader.Token, reader.Value, type);
}
}
In your case you want it to produce something like:
Token Value Type
------------------------------------------
ObjectStart
PropertyName name System.String
String Bill System.String
PropertyName age System.String
Int 32 System.Int32
PropertyName awake System.String
Boolean True System.Boolean
PropertyName n System.String
Double 1994.0226 System.Double
ObjectEnd
It just occured to me that you'll always have at least one object. So you should read 'ObjectStart' once. If it occurs more than once then you know the file has not the expected format. Otherwise you can process the file.
Related
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
This is my below JSON
{
"status": "OK",
"Response": [{
"id": 43,
"Name": "name 1",
"SubName": "Sub 1"
"Link": "Link 1",
"Active": 1,
"Genre": 8,
"Description": "Description 1",
"Languages": "",
"IsDeleted": 0,
"GenreId": 8
},
{
"id": 44,
"Name": "name 1",
"SubName": "Sub 2"
"Link": "Link 2",
"Active": 1,
"Genre": 9,
"Description": "Description 2",
"Languages": "",
"IsDeleted": 0,
"GenreId": 9
},
{
"id": 45,
"Name": "name 1",
"SubName": "Sub 3"
"Link": "Link 3",
"Active": 1,
"Genre": 10,
"Description": "Description 3",
"Languages": "",
"IsDeleted": 0,
"GenreId": 10
},
{
"id": 46,
"Name": "name 2",
"SubName": ""
"Link": "Link 4",
"Active": 1,
"Genre": 11,
"Description": "Description 4",
"Languages": "",
"IsDeleted": 0,
"GenreId": 11
},
{
"id": 47,
"Name": "name 3",
"SubName": "Sub 1"
"Link": "Link 5",
"Active": 1,
"Genre": 12,
"Description": "Description 5",
"Languages": "",
"IsDeleted": 0,
"GenreId": 12
},
{
"id": 48,
"Name": "name 3",
"SubName": "Sub 2"
"Link": "Link 6",
"Active": 1,
"Genre": 13,
"Description": "Description 6",
"Languages": "",
"IsDeleted": 0,
"GenreId": 13
},
{
"id": 49,
"Name": "name 3",
"SubName": "Sub 3"
"Link": "Link 7",
"Active": 1,
"Genre": 14,
"Description": "Description 7",
"Languages": "",
"IsDeleted": 0,
"GenreId": 14
},
{
"id": 50,
"Name": "name 3",
"SubName": "Sub 4"
"Link": "Link 8",
"Active": 1,
"Genre": 15,
"Description": "Description 8",
"Languages": "",
"IsDeleted": 0,
"GenreId": 15
},
{
"id": 51,
"Name": "name 4",
"SubName": ""
"Link": "Link 9",
"Active": 1,
"Genre": 16,
"Description": "Description 9",
"Languages": "",
"IsDeleted": 0,
"GenreId": 16
}]
}
and I tried to make like below JSON
name 1.json
{
"rows": [{
"title": "Sub 1",
"items": [{
"id": 43,
"Name": "name 1",
"SubName": "Sub 1"
"Link": "Link 1",
"Active": 1,
"Genre": 8,
"Description": "Description 1",
"Languages": "",
"IsDeleted": 0,
"GenreId": 8
}]
},
{
"title": "Sub 2",
"items": [{
""id": 44,
"Name": "name 1",
"SubName": "Sub 2"
"Link": "Link 2",
"Active": 1,
"Genre": 9,
"Description": "Description 2",
"Languages": "",
"IsDeleted": 0,
"GenreId": 9
}]
},
{
"title": "Sub 3",
"items": [{
""id": 45,
"Name": "name 1",
"SubName": "Sub 3"
"Link": "Link 3",
"Active": 1,
"Genre": 10
"Description": "Description 3",
"Languages": "",
"IsDeleted": 0,
"GenreId": 10
}]
}
}]
}
name 3.json
{
"rows": [{
"title": "Sub 1",
"items": [{
"id": 47,
"Name": "name 3",
"SubName": "Sub 1"
"Link": "Link 5",
"Active": 1,
"Genre": 12,
"Description": "Description 5",
"Languages": "",
"IsDeleted": 0,
"GenreId": 12
}]
},
{
"title": "Sub 2",
"items": [{
""id": 48,
"Name": "name 3",
"SubName": "Sub 2"
"Link": "Link 6",
"Active": 1,
"Genre": 13,
"Description": "Description 6",
"Languages": "",
"IsDeleted": 0,
"GenreId": 13
}]
},
{
"title": "Sub 3",
"items": [{
""id": 49,
"Name": "name 3",
"SubName": "Sub 3"
"Link": "Link 7",
"Active": 1,
"Genre": 14
"Description": "Description 7",
"Languages": "",
"IsDeleted": 0,
"GenreId": 14
}]
},
{
"title": "Sub 4",
"items": [{
""id": 50,
"Name": "name 3",
"SubName": "Sub 4"
"Link": "Link 8",
"Active": 1,
"Genre": 15
"Description": "Description 8",
"Languages": "",
"IsDeleted": 0,
"GenreId": 15
}]
}
}]
}
I'm trying with the duplicate name wise separate a JSON like above. I found only duplicate name and nothing else in JSON.
Does anyone know how to fetch the duplicate value?
I tried with the Linq query and used
mygeneratedresponse.Skip(1).ToList();
It's working. But is there a better solution?
I'm not sure if is this what you're looking for but, follow a way to get duplicate values grouping it with linq;
you just need to create a consoleapp and add newtonsoft.json to it, to run the code bellow.
class Program
{
static string pathA = "<place-your-first-json-location-here>"; //ex: c:\test\test.json
static void Main(string[] args)
{
var json = JsonConvert.DeserializeObject<Test>(File.ReadAllText(pathA));
var filteredByName = json.Response.GroupBy(g => g.Name).OrderBy(o => o.Key).ToList();
foreach (var item in filteredByName)
{
Console.WriteLine($"Name: {item.Key} Qty response: {item.Count()}" );
}
}
}
public class Test {
public string Status { get; set; }
public List<Response> Response { get; set; }
}
public class Response {
public int Id { get; set; }
public string Name { get; set; }
public string SubName { get; set; }
public string Link { get; set; }
public int Active { get; set; }
public int Genre { get; set; }
public string Description { get; set; }
public string Languages { get; set; }
public int IsDeleted { get; set; }
public int GenreId { get; set; }
}
this is the expected output, so you can go on and apply it to your logic;
Name: name 1 Qty response: 3
Name: name 2 Qty response: 1
Name: name 3 Qty response: 4
Name: name 4 Qty response: 1
The below code will generate your expected output:
this code is also place at .net fiddle https://dotnetfiddle.net/d2uSNC
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
public class Program
{
public static void Main()
{
var jsonString = "{ \"status\": \"OK\", \"Response\": [{ \"id\": 43, \"Name\": \"name 1\", \"SubName\": \"Sub 1\", \"Link\": \"Link 1\", \"Active\": 1, \"Genre\": 8, \"Description\": \"Description 1\", \"Languages\": \"\", \"IsDeleted\": 0, \"GenreId\": 8 }, { \"id\": 44, \"Name\": \"name 1\", \"SubName\": \"Sub 2\", \"Link\": \"Link 2\", \"Active\": 1, \"Genre\": 9, \"Description\": \"Description 2\", \"Languages\": \"\", \"IsDeleted\": 0, \"GenreId\": 9 }, { \"id\": 45, \"Name\": \"name 1\", \"SubName\": \"Sub 3\", \"Link\": \"Link 3\", \"Active\": 1, \"Genre\": 10, \"Description\": \"Description 3\", \"Languages\": \"\", \"IsDeleted\": 0, \"GenreId\": 10 }, { \"id\": 46, \"Name\": \"name 2\", \"SubName\": \"\", \"Link\": \"Link 4\", \"Active\": 1, \"Genre\": 11, \"Description\": \"Description 4\", \"Languages\": \"\", \"IsDeleted\": 0, \"GenreId\": 11 }, { \"id\": 47, \"Name\": \"name 3\", \"SubName\": \"Sub 1\", \"Link\": \"Link 5\", \"Active\": 1, \"Genre\": 12, \"Description\": \"Description 5\", \"Languages\": \"\", \"IsDeleted\": 0, \"GenreId\": 12 }, { \"id\": 48, \"Name\": \"name 3\", \"SubName\": \"Sub 2\", \"Link\": \"Link 6\", \"Active\": 1, \"Genre\": 13, \"Description\": \"Description 6\", \"Languages\": \"\", \"IsDeleted\": 0, \"GenreId\": 13 }, { \"id\": 49, \"Name\": \"name 3\", \"SubName\": \"Sub 3\", \"Link\": \"Link 7\", \"Active\": 1, \"Genre\": 14, \"Description\": \"Description 7\", \"Languages\": \"\", \"IsDeleted\": 0, \"GenreId\": 14 }, { \"id\": 50, \"Name\": \"name 3\", \"SubName\": \"Sub 4\", \"Link\": \"Link 8\", \"Active\": 1, \"Genre\": 15, \"Description\": \"Description 8\", \"Languages\": \"\", \"IsDeleted\": 0, \"GenreId\": 15 }, { \"id\": 51, \"Name\": \"name 4\", \"SubName\": \"\", \"Link\": \"Link 9\", \"Active\": 1, \"Genre\": 16, \"Description\": \"Description 9\", \"Languages\": \"\", \"IsDeleted\": 0, \"GenreId\": 16 }]}";
var json = JsonConvert.DeserializeObject<Root>(jsonString);
var filteredByName = json.Response.GroupBy(g => g.Name).OrderBy(o => o.Key).ToList();
foreach (var item in filteredByName)
{
var fileObject = item.GroupBy(x=>x.SubName).Select(s=> new { title =s.Key, items= s.ToList()});
var fileJson = JsonConvert.SerializeObject(fileObject, Formatting.Indented);
Console.WriteLine("" + item.Key +".json");
Console.WriteLine(fileJson);
}
}
}
public class JsonResponse {
public int id { get; set; }
public string Name { get; set; }
public string SubName { get; set; }
public string Link { get; set; }
public int Active { get; set; }
public int Genre { get; set; }
public string Description { get; set; }
public string Languages { get; set; }
public int IsDeleted { get; set; }
public int GenreId { get; set; }
}
public class Root {
public string status { get; set; }
public List<JsonResponse> Response { get; set; }
}
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.
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.
I am attempting to deserialize a JSON response from a webserver which I have no control over. As you can see below the resulting object is returned as a JSONObject. The issue with this is that the key of each object is unique to every player. As far as I can tell I am required to create a separate class for each unique JSONObject to deserialize the string properly which simply would not work considering the key for each object is unique to each created account that is returned from the webserver. I want to know if it is possible to deserialize the JSONObject "players" as a JSONArray or if I am overthinking this a bit too much. The ammount of players returned in the list also varies for up to a maximum of 32.
{
"players": {
"930153636": {
"name": "ur_moms_cookies",
"tag": "",
"rank": 62,
"score": 1332,
"kills": 9,
"deaths": 2,
"squad": 1,
"role": 1
},
"250721735": {
"name": "PyRobotic",
"tag": "",
"rank": 5,
"score": 1786,
"kills": 8,
"deaths": 4,
"squad": 2,
"role": 1
},
"1035406266": {
"name": "ShrapnalFire",
"tag": "GaGu",
"rank": 60,
"score": 1455,
"kills": 8,
"deaths": 7,
"squad": 1,
"role": 1
},
"239767512": {
"name": "NeoEllis",
"tag": "",
"rank": 77,
"score": 3244,
"kills": 20,
"deaths": 6,
"squad": 3,
"role": 1
},
"936400786": {
"name": "antiares51",
"tag": "",
"rank": 140,
"score": 4720,
"kills": 17,
"deaths": 2,
"squad": 2,
"role": 1
},
"355364783": {
"name": "BombKat11",
"tag": "",
"rank": 16,
"score": 1347,
"kills": 9,
"deaths": 5,
"squad": 4,
"role": 1
},
"803046096": {
"name": "thejoedude",
"tag": "FSJ",
"rank": 66,
"score": 1294,
"kills": 8,
"deaths": 8,
"squad": 4,
"role": 1
},
"788221305": {
"name": "Tiyou33",
"tag": "",
"rank": 45,
"score": 1927,
"kills": 4,
"deaths": 5,
"squad": 2,
"role": 1
},
"353394766": {
"name": "DKOfTFC",
"tag": "RSPN",
"rank": 119,
"score": 1895,
"kills": 9,
"deaths": 4,
"squad": 4,
"role": 1
},
"370847289": {
"name": "shohet10",
"tag": "",
"rank": 40,
"score": 1570,
"kills": 7,
"deaths": 7,
"squad": 6,
"role": 1
},
"206872615": {
"name": "me94132",
"tag": "",
"rank": 60,
"score": 2045,
"kills": 7,
"deaths": 4,
"squad": 3,
"role": 1
},
"332317870": {
"name": "frehgv",
"tag": "",
"rank": 48,
"score": 713,
"kills": 3,
"deaths": 4,
"squad": 4,
"role": 1
},
"1144758913": {
"name": "MudCruncher_78",
"tag": "",
"rank": 61,
"score": 1822,
"kills": 7,
"deaths": 5,
"squad": 6,
"role": 1
},
"603412175": {
"name": "UsedTissue",
"tag": "",
"rank": 119,
"score": 1551,
"kills": 10,
"deaths": 1,
"squad": 1,
"role": 1
},
"1655466910": {
"name": "JackTheRipp3r2",
"tag": "",
"rank": 27,
"score": 797,
"kills": 2,
"deaths": 3,
"squad": 8,
"role": 1
},
"869745436": {
"name": "Negibou",
"tag": "",
"rank": 139,
"score": 4792,
"kills": 14,
"deaths": 4,
"squad": 2,
"role": 1
},
"447652633": {
"name": "RufusTheRabbit",
"tag": "",
"rank": 91,
"score": 1468,
"kills": 7,
"deaths": 4,
"squad": 4,
"role": 1
},
"352650707": {
"name": "DJ1101",
"tag": "",
"rank": 28,
"score": 847,
"kills": 5,
"deaths": 6,
"squad": 3,
"role": 1
},
"855246326": {
"name": "-Frigadier-",
"tag": "",
"rank": 109,
"score": 667,
"kills": 1,
"deaths": 6,
"squad": 1,
"role": 1
},
"255855183": {
"name": "Asakajim",
"tag": "",
"rank": 6,
"score": 514,
"kills": 0,
"deaths": 8,
"squad": 8,
"role": 1
},
"248119620": {
"name": "Kokovec",
"tag": "FCM",
"rank": 121,
"score": 891,
"kills": 5,
"deaths": 3,
"squad": 8,
"role": 1
},
"348016421": {
"name": "pandaymd",
"tag": "",
"rank": 122,
"score": 1595,
"kills": 6,
"deaths": 9,
"squad": 2,
"role": 1
},
"250545778": {
"name": "Vulkkann",
"tag": "",
"rank": 40,
"score": 2323,
"kills": 14,
"deaths": 8,
"squad": 3,
"role": 1
},
"949941984": {
"name": "WarchiefBigzb",
"tag": "",
"rank": 70,
"score": 1013,
"kills": 5,
"deaths": 3,
"squad": 9,
"role": 1
},
"268773188": {
"name": "Brutuka",
"tag": "",
"rank": 48,
"score": 952,
"kills": 5,
"deaths": 4,
"squad": 5,
"role": 1
},
"801259600": {
"name": "gpc4567",
"tag": "",
"rank": 109,
"score": 1710,
"kills": 11,
"deaths": 5,
"squad": 3,
"role": 1
},
"338093557": {
"name": "Zelios86",
"tag": "",
"rank": 140,
"score": 1400,
"kills": 7,
"deaths": 4,
"squad": 8,
"role": 1
},
"364705773": {
"name": "Fleischwolfx",
"tag": "",
"rank": 121,
"score": 1863,
"kills": 13,
"deaths": 2,
"squad": 5,
"role": 1
},
"173524306": {
"name": "BlackDynamite901",
"tag": "",
"rank": 75,
"score": 583,
"kills": 4,
"deaths": 2,
"squad": 9,
"role": 1
},
"339527854": {
"name": "Xixus",
"tag": "",
"rank": 21,
"score": 0,
"kills": 0,
"deaths": 0,
"squad": 1,
"role": 1
},
"1667184018": {
"name": "BckBone71",
"tag": "",
"rank": 35,
"score": 98,
"kills": 1,
"deaths": 1,
"squad": 5,
"role": 1
}
}
}
Thus far I have tried a few variations of something along the lines of the below code snippet which of course does not work since the players object isn't an array.
public class Team
{
public int faction;
[JsonProperty("players")]
public List<Player> players { get; set; }
}
public class Player
{
public string name;
public string tag;
public int rank;
}
Try something like this:
var players = new List<Player>();
dynamic dObject = JObject.Parse(JSON);
foreach (var property in dObject.players) {
var player = property.Value;
var playerModel = new Player {
Name = player.name,
Tag = player.tag,
Rank = player.rank
};
players.Add(playerModel);
}
Where JSON is your Json object. In this case, I just made it a string literal to test your object. This is using NewtonSoft.Json for the parsing.
Once you get the player, you should have access to all of its properties and not have to worry about the unique player ID.
Here is the .NET fiddle: https://dotnetfiddle.net/9iOT5w.