How do you read Json data sent by SQL Server in C#? - c#

I have created a stored procedure which returns JSON data:
ALTER PROCEDURE SpEmployeeSel
AS
BEGIN
SET NOCOUNT ON;
SELECT ve.*
FROM dbo.VwEmployee AS ve
FOR JSON PATH, INCLUDE_NULL_VALUES
END;
This query outputs:
[
{
"PersonId": 4,
"FirstName": "Anuj",
"MiddleName": "",
"LastName": "Tamrakar",
"DateofBirth": "2018-01-04T00:00:00",
"EmployeeId": 1,
"EmployeeCode": "Emp1",
"DesignationId": 1,
"DesignationName": "Ceo",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:16:00"
},
{
"PersonId": 5,
"FirstName": "John",
"MiddleName": "",
"LastName": "Pradhan",
"DateofBirth": "2018-01-04T00:00:00",
"EmployeeId": 2,
"EmployeeCode": "Emp2",
"DesignationId": 2,
"DesignationName": "Human Resource",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:17:00"
},
{
"PersonId": 6,
"FirstName": "Priyanka",
"MiddleName": "",
"LastName": "Khadgi",
"DateofBirth": "2018-01-03T00:00:00",
"EmployeeId": 3,
"EmployeeCode": "Emp3",
"DesignationId": 1,
"DesignationName": "Ceo",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:16:00"
},
{
"PersonId": 10,
"FirstName": "Sakar",
"MiddleName": "",
"LastName": "Thapa",
"DateofBirth": "2018-01-09T00:00:00",
"EmployeeId": 7,
"EmployeeCode": "Emp4",
"DesignationId": 1,
"DesignationName": "Ceo",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:16:00"
},
{
"PersonId": 11,
"FirstName": "Aaa",
"MiddleName": "",
"LastName": "asdfasf",
"DateofBirth": "2018-01-03T00:00:00",
"EmployeeId": 8,
"EmployeeCode": "Emp5",
"DesignationId": 2,
"DesignationName": "Human Resource",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:17:00"
},
{
"PersonId": 12,
"FirstName": "Bibek",
"MiddleName": "",
"LastName": "Thapa",
"DateofBirth": "2018-01-11T00:00:00",
"EmployeeId": 9,
"EmployeeCode": "Emp6",
"DesignationId": 3,
"DesignationName": "Staff",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:17:00"
},
{
"PersonId": 13,
"FirstName": "dafgasdf",
"MiddleName": "",
"LastName": "asfsdf",
"DateofBirth": "2018-01-12T00:00:00",
"EmployeeId": 10,
"EmployeeCode": "Emp7",
"DesignationId": 1,
"DesignationName": "Ceo",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:16:00"
},
{
"PersonId": 14,
"FirstName": "sdfsdf",
"MiddleName": "asdfsdaf",
"LastName": "asdfasdf",
"DateofBirth": "2018-01-03T00:00:00",
"EmployeeId": 11,
"EmployeeCode": "Emp8",
"DesignationId": 2,
"DesignationName": "Human Resource",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:17:00"
},
{
"PersonId": 15,
"FirstName": "Asdfasf",
"MiddleName": "asdf",
"LastName": "asdfasf",
"DateofBirth": "2018-01-05T00:00:00",
"EmployeeId": 12,
"EmployeeCode": "Emp9",
"DesignationId": 2,
"DesignationName": "Human Resource",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:17:00"
},
{
"PersonId": 16,
"FirstName": "asdfasf",
"MiddleName": "aasdfa",
"LastName": "asdfasf",
"DateofBirth": "2018-01-12T00:00:00",
"EmployeeId": 13,
"EmployeeCode": "Emp10",
"DesignationId": 1,
"DesignationName": "Ceo",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:16:00"
},
{
"PersonId": 17,
"FirstName": "1111123123",
"MiddleName": "asdfasd",
"LastName": "asdfasdf",
"DateofBirth": "2018-01-05T00:00:00",
"EmployeeId": 14,
"EmployeeCode": "Emp11",
"DesignationId": 2,
"DesignationName": "Human Resource",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:17:00"
}
]
You can see the procedure outputs the expected json data in a single column.
Now in Visual Studio, I tried calling the procedure through ADO.NET like this
SqlConnection conn = new SqlConnection("//connection string path");
conn.Open();
SqlCommand command = new SqlCommand("SpEmployeeSEl", conn);
command.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
SqlDataAdapter sta = new SqlDataAdapter(command);
sta.Fill(dt);
conn.Close();
string result = dt.Rows[0][0].ToString();
Now When I look at the output result I only get half of the json data like below:
[
{
"PersonId": 4,
"FirstName": "Anuj",
"MiddleName": "",
"LastName": "Tamrakar",
"DateofBirth": "2018-01-04T00:00:00",
"EmployeeId": 1,
"EmployeeCode": "Emp1",
"DesignationId": 1,
"DesignationName": "Ceo",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:16:00"
},
{
"PersonId": 5,
"FirstName": "John",
"MiddleName": "",
"LastName": "Pradhan",
"DateofBirth": "2018-01-04T00:00:00",
"EmployeeId": 2,
"EmployeeCode": "Emp2",
"DesignationId": 2,
"DesignationName": "Human Resource",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:17:00"
},
{
"PersonId": 6,
"FirstName": "Priyanka",
"MiddleName": "",
"LastName": "Khadgi",
"DateofBirth": "2018-01-03T00:00:00",
"EmployeeId": 3,
"EmployeeCode": "Emp3",
"DesignationId": 1,
"DesignationName": "Ceo",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:16:00"
},
{
"PersonId": 10,
"FirstName": "Sakar",
"MiddleName": "",
"LastName": "Thapa",
"DateofBirth": "2018-01-09T00:00:00",
"EmployeeId": 7,
"EmployeeCode": "Emp4",
"DesignationId": 1,
"DesignationName": "Ceo",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:16:00"
},
{
"PersonId": 11,
"FirstName": "Aaa",
"MiddleName": "",
"LastName": "asdfasf",
"DateofBirth": "2018-01-03T00:00:00",
"EmployeeId": 8,
"EmployeeCode": "Emp5",
"DesignationId": 2,
"DesignationName": "Human Resource",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:17:00"
},
{
"PersonId": 12,
"FirstName": "Bibek",
"MiddleName": "",
"LastName": "Thapa",
"DateofBirth": "2018-01-11T00:00:00",
"EmployeeId": 9,
"EmployeeCode": "Emp6",
"DesignationId": 3,
"DesignationName": "Staff",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:17:00"
},
{
"PersonId": 13,
"FirstName": "dafgasdf",
"MiddleName": "",
"LastName": "asfsdf",
"DateofBirth": "2018-01-12T00:00:00",
"EmployeeId": 10,
"EmployeeCode": "Emp7",
"DesignationId": 1,
"DesignationName": "Ceo",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:16:00"
},
{
"PersonId": 14,
"FirstName": "sdfsdf",
"MiddleName": "asdfsdaf",
"LastName": "asdfasdf",
"DateofBirth": "2018-01-03T00:00:00",
"EmployeeId": 11,
"EmployeeCode": "Emp8",
"DesignationId": 2,
"DesignationName": "Human Resource",
"InsertPersonId": 1,
"InsertDate": "2018-01-20T02:17:00"
},
{
"PersonId": 15,
"FirstName": "Asdfasf",
"MiddleName": "asdf
The json string terminates in middle.
I tried looking the content of dataTable and there the string was broken into two rows which caused the the code dt.Rows[0][0].ToString() to return only first row and this is the root cause of the problem.
So I don't know why the string was broken down into two rows.
I then tried calling the procedure with entity framework like this:
string result;
using (AccountingEntities db = new AccountingEntities())
{
result = db.SpEmployeeSel().FirstOrDefault();
}
But the result was same as Ado.Net with broken json string.
I would really be grateful if you guys give solution of Entity Framework rather than in ADO.NET. Since my application uses Entity Framework.
UPDATE:
Workaround That I did for Entity Framework:
string jsonresult;
using (AccountingEntities db = new AccountingEntities())
{
List<string> jsonlist= db.SpTestSEl().ToList();
jsonresult = String.Join("", jsonlist.ToArray());
}
Workaround that I did for Ado.net :
https://learn.microsoft.com/en-us/sql/relational-databases/json/use-for-json-output-in-sql-server-and-in-client-apps-sql-server
Note: Entity framework sucks.

I havent tried this whether its working this is one solution i found please try it and see.
var queryWithForJson = "SELECT ... FOR JSON";
var conn = new SqlConnection("<connection string>");
var cmd = new SqlCommand(queryWithForJson, conn);
conn.Open();
var jsonResult = new StringBuilder();
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}

Related

How to convert JSON string to C# IEnumerable<JToken>

so i'm getting a json file from the web into my program that reads something like this:
{
"10": {
"appid": 10,
"name": "Counter-Strike",
"developer": "Valve",
"publisher": "Valve",
"score_rank": "",
"positive": 183964,
"negative": 4782,
"userscore": 0,
"owners": "10,000,000 .. 20,000,000",
"average_forever": 11228,
"average_2weeks": 289,
"median_forever": 210,
"median_2weeks": 114,
"price": "999",
"initialprice": "999",
"discount": "0",
"ccu": 13567
},
"20": {
"appid": 20,
"name": "Team Fortress Classic",
"developer": "Valve",
"publisher": "Valve",
"score_rank": "",
"positive": 5223,
"negative": 871,
"userscore": 0,
"owners": "2,000,000 .. 5,000,000",
"average_forever": 522,
"average_2weeks": 0,
"median_forever": 20,
"median_2weeks": 0,
"price": "499",
"initialprice": "499",
"discount": "0",
"ccu": 93
},
"30": {
"appid": 30,
"name": "Day of Defeat",
"developer": "Valve",
"publisher": "Valve",
"score_rank": "",
"positive": 4866,
"negative": 543,
"userscore": 0,
"owners": "5,000,000 .. 10,000,000",
"average_forever": 2191,
"average_2weeks": 343,
"median_forever": 24,
"median_2weeks": 343,
"price": "499",
"initialprice": "499",
"discount": "0",
"ccu": 130
},
"40": {
"appid": 40,
"name": "Deathmatch Classic",
"developer": "Valve",
"publisher": "Valve",
"score_rank": "",
"positive": 1789,
"negative": 400,
"userscore": 0,
"owners": "5,000,000 .. 10,000,000",
"average_forever": 297,
"average_2weeks": 0,
"median_forever": 8,
"median_2weeks": 0,
"price": "499",
"initialprice": "499",
"discount": "0",
"ccu": 6
}
I'm importing it has a string how can I get an enumerable or list where I get all the tokens as (Jtokens) so "IEnumerable<JToken> or List<JToken>" like ["10", "40", "60"...]
This is what my code looks like right now:
string json = webClient.DownloadString("https://api.steampowered.com/ISteamApps/GetAppList/v2/");
tokens = JObject.Parse(json).Children();
//token = JObject.Parse(json).SelectToken("applist.apps");
for (int i = 0; i < tokens.Count(); i++)
{
int currentID = (int)tokens.ElementAt(i).SelectToken("appid");
if (SteamApps.BIsSubscribedApp(new AppId_t((uint)currentID)))
{
threads.Add(new Thread(new ParameterizedThreadStart(AddToDictionary)));
threads.Last().Start(new stats(i, currentID, threads.Last()));
}
}
But this isn't working at all and I can't read any values..
There are oodles of ways to do this and variations. However, this is simple enough. The premise is Parse -> Select First -> Target property by name
var results = JToken.Parse(input)
// Select past the dictionary
.Select(x => x.First())
// project property values in to a value tuple
.Select(x => (Appid: x["appid"], Name: x["name"]))
.ToArray();
foreach (var item in results)
Console.WriteLine(item);
Output
(10, Counter-Strike)
(20, Team Fortress Classic)
(30, Day of Defeat)
(40, Deathmatch Classic)
by selecting the token u want from the list of objects that was deserialised from the json string using system.linq
newlist = deserList.Select(x => x.Jtoken);

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

How to fetch the duplicate data from single field using key pair value in LINQ?

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; }
}

Check if a json file is a dictionary

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.

How to deserialize JSONObject as JSONArray in C#

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.

Categories

Resources