Related
I'm trying to access data from JSON file though i am only able to extract the name while others aren't showing. I have attached both my JSON file and my C# script from unity. The Item Class list data which needs to be extracted from the JSON file i.e name, gameId, message etc.
What is Captured when running.
Here is my code - JSONreader
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JSONreader : MonoBehaviour
{
public TextAsset txtJson;
[System.Serializable]
public class ItemList
{
public Item item;
}
[System.Serializable]
public class Item
{
public string name;
public string request;
public string key;
public string value;
public string raw;
public string type;
public string header;
public string gameId;
public float amount;
public string orderId;
public int code;
public string message;
public string transactionId;
public string description;
}
public ItemList itemList = new ItemList();
private void Start()
{
itemList = JsonUtility.FromJson<ItemList>(txtJson.text);
}
private void Update()
{
}
}
my JSON file
{
"name": "Purchase API",
"protocolProfileBehavior": {
"disabledSystemHeaders": {
"accept": true,
"user-agent": true
}
},
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6InIxTGtiQm8zOTI1UmIyWkZGckt5VTNNVmV4OVQyODE3S3gwdmJpNmlfS2MifQ.eyJuYW1lIjoiU2FtcGxlIEFkbWluIFVzZXIiLCJuaWNrbmFtZSI6InRoZWFkbWluIiwiYmlvIjpudWxsLCJzdWIiOiI0MTk0NjEzYi02MTI0LTQyN2UtODk2NC0yYWY1ZGNiM2UzZjIiLCJub25jZSI6IjEyMyIsInNfaGFzaCI6ImpTUFBiSWJvTktlcWJ0N1ZUQ2JPS3ciLCJhdWQiOiJmNGQ3MTE4YS1iY2UyLTExZWMtOTliNC05ZWI3NDRmNWJiZTIiLCJleHAiOjE2NTM5MzQ1MDQsImlhdCI6MTY1MzkzMDkwNCwiaXNzIjoiaHR0cHM6Ly9pZC5qaXdlLmlvIn0.tquqwYt8htiZd27au4R4H6Zjd1VqzNJGw5xZCEQ8NRlrQvmudUz-uo4qdHNW9k71w6Di3H-qMdliuFgj7sJb0naDNIScEalw1xPlA0R8QyIB6JT8YFiAANAfYvIaM4DWYeagDdia3MXJoRnnWxgg57yzd-ZA_ws3-brh-I-1mulRiGQcZ8wgpRhk4Vp3xjvNa3FcsyJ7excPTiD5zaSdtKGSJ3J2RSOAt5n2m-R-QGe_1lwAXXR-sa7P77tyG4FmQ2gHtmCRRnZzVD0AM6fULYWwYURARTwiCki2HYWCNJsMplID99Hx5JOHzwViHtV6XioRelk0t3Gef7Jqd2gYqg",
"type": "string"
}
]
},
"method": "POST",
"header": [
{
"key": "api_secret",
"value": "5e3ca84dad0758595a8dc793beb509505e79998bac87ffde128c668ac0215a1ed0462407ac794e99b26041cc3eab266cd06ced0d530b6d02d024d6b49353dd8d",
"type": "text"
},
{
"key": "api_key",
"value": "hasuraengine",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"gameId\": \"JiweGameID\",\n \"amount\": 1,\n \"orderId\": \"OrderID Generated On GameDev Side\",\n \"description\": \"Charlie's Test\",\n \"applyTransactionFeeOn\": \"SENDER\",\n \"idempotencyKey\": \"SOME_KEY#2\",\n \"metadata\": {\n \"key\": \"value\"\n }\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "https://bursment.jiwe.io/api/v1/cowrie/purchases",
"protocol": "https",
"host": [
"bursment",
"jiwe",
"io"
],
"path": [
"api",
"v1",
"cowrie",
"purchases"
]
}
},
"response": [
{
"name": "Purchase API",
"originalRequest": {
"method": "POST",
"header": [
{
"key": "api_secret",
"value": "5e3ca84dad0758595a8dc793beb509505e79998bac87ffde128c668ac0215a1ed0462407ac794e99b26041cc3eab266cd06ced0d530b6d02d024d6b49353dd8d",
"type": "text"
},
{
"key": "api_key",
"value": "hasuraengine",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"gameId\": \"JiweGameID\",\n \"amount\": 1,\n \"orderId\": \"OrderID Generated On GameDev Side\",\n \"description\": \"Charlie's Test\",\n \"applyTransactionFeeOn\": \"SENDER\",\n \"idempotencyKey\": \"SOME_KEY#2\",\n \"metadata\": {\n \"key\": \"value\"\n }\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "https://bursment.jiwe.io/api/v1/cowrie/purchases",
"protocol": "https",
"host": [
"bursment",
"jiwe",
"io"
],
"path": [
"api",
"v1",
"cowrie",
"purchases"
]
}
},
"status": "OK",
"code": 200,
"_postman_previewlanguage": "json",
"header": [
{
"key": "Server",
"value": "nginx/1.14.0 (Ubuntu)"
},
{
"key": "Date",
"value": "Mon, 30 May 2022 18:40:17 GMT"
},
{
"key": "Content-Type",
"value": "application/json; charset=utf-8"
},
{
"key": "Content-Length",
"value": "135"
},
{
"key": "Connection",
"value": "keep-alive"
},
{
"key": "Vary",
"value": "Origin"
},
{
"key": "Rate-Limit-Remaining",
"value": "53"
},
{
"key": "Rate-Limit-Reset",
"value": "1653936052"
},
{
"key": "Rate-Limit-Total",
"value": "60"
},
{
"key": "X-DNS-Prefetch-Control",
"value": "off"
},
{
"key": "X-Frame-Options",
"value": "SAMEORIGIN"
},
{
"key": "Strict-Transport-Security",
"value": "max-age=15552000; includeSubDomains"
},
{
"key": "X-Download-Options",
"value": "noopen"
},
{
"key": "X-Content-Type-Options",
"value": "nosniff"
},
{
"key": "X-XSS-Protection",
"value": "1; mode=block"
}
],
"cookie": [],
"body": "{\n \"code\": \"200\",\n \"type\": \"SUCCESS\",\n \"message\": \"Purchase successful\",\n \"transactionId\": \"f3a4ff6c-e047-11ec-80ac-000d3a9bae12\"\n}"
}
]
},
I want to be able to query my json file dynamically to get the following:
"CustomerID":{"value":"TCHCHIP0111"}
from this file:
[{
"id": "62f687e7-eaa4-4999-b44a-5ccbc249bf34",
"rowNumber": 1,
"note": "",
"AccountRef": {
"value": "CP6000256"
},
"ApplyOverdueCharges": {
"value": false
},
"AutoApplyPayments": {
"value": false
},
"BillingAddressSameAsMain": {
"value": true
},
"BillingContactSameAsMain": {
"value": true
},
"CreatedDateTime": {
"value": "2019-09-20T14:17:22.343+02:00"
},
"CurrencyID": {
"value": "NAD"
},
"CurrencyRateType": {
"value": "SPOT"
},
"CustomerClass": {
"value": "PNP"
},
"CustomerID": {
"value": "TCHCHIP0111"
},
"CustomerName": {
"value": "Pick & Pay Retail C/kins Oshak"
},
"EnableCurrencyOverride": {
"value": false
},
"EnableRateOverride": {
"value": false
},
"EnableWriteOffs": {
"value": false
},
"FOBPoint": {
"value": "CP60"
},
"GLNNumber": {
"value": "WN051000004279"
},
"LastModifiedDateTime": {
"value": "2019-10-24T12:42:53.383+02:00"
},
"LeadTimedays": {},
"LocationName": {
"value": "Primary Location"
},
"MultiCurrencyStatements": {
"value": false
},
"OrderPriority": {
"value": 0
},
"ParentRecord": {
"value": "TCHCHIPPNP"
},
"PriceClassID": {
"value": "PNP"
},
"PrintInvoices": {
"value": false
},
"PrintStatements": {
"value": false
},
"ResidentialDelivery": {
"value": false
},
"SaturdayDelivery": {
"value": false
},
"SendInvoicesbyEmail": {
"value": false
},
"SendStatementsbyEmail": {
"value": false
},
"ShippingAddressSameAsMain": {
"value": false
},
"ShippingBranch": {},
"ShippingContactSameAsMain": {
"value": false
},
"ShippingRule": {
"value": "Cancel Remainder"
},
"ShippingTerms": {},
"ShippingZoneID": {},
"ShipVia": {},
"StatementCycleID": {
"value": "ENDOFMONTH"
},
"StatementType": {
"value": "Open Item"
},
"Status": {
"value": "Active"
},
"TaxRegistrationID": {},
"TaxZone": {
"value": "RECEIVER"
},
"Terms": {
"value": "30D STATE"
},
"WarehouseID": {},
"WriteOffLimit": {
"value": 0.0000
},
"custom": {},
"files": []
}, {
"id": "445d97c3-411d-4587-ac86-8f84267c4324",
"rowNumber": 2,
"note": "",
"AccountRef": {
"value": "NC6000014"
},
"ApplyOverdueCharges": {
"value": false
},
"AutoApplyPayments": {
"value": false
},
"BillingAddressSameAsMain": {
"value": true
},
"BillingContactSameAsMain": {
"value": true
},
"CreatedDateTime": {
"value": "2019-09-20T14:14:15.95+02:00"
},
"CurrencyID": {
"value": "NAD"
},
"CurrencyRateType": {
"value": "SPOT"
},
"CustomerClass": {
"value": "PNP"
},
"CustomerID": {
"value": "TCRDMIC0111"
},
"CustomerName": {
"value": "Pick & Pay Dairy Maid Oshakati"
},
"EnableCurrencyOverride": {
"value": false
},
"EnableRateOverride": {
"value": false
},
"EnableWriteOffs": {
"value": false
},
"FOBPoint": {
"value": "IC60"
},
"GLNNumber": {
"value": "WN051000004279"
},
"LastModifiedDateTime": {
"value": "2019-10-24T10:56:49.463+02:00"
},
"LeadTimedays": {},
"LocationName": {
"value": "Primary Location"
},
"MultiCurrencyStatements": {
"value": false
},
"OrderPriority": {
"value": 0
},
"ParentRecord": {
"value": "TCRDMICPNP"
},
"PriceClassID": {
"value": "PNP"
},
"PrintInvoices": {
"value": false
},
"PrintStatements": {
"value": false
},
"ResidentialDelivery": {
"value": false
},
"SaturdayDelivery": {
"value": false
},
"SendInvoicesbyEmail": {
"value": false
},
"SendStatementsbyEmail": {
"value": false
},
"ShippingAddressSameAsMain": {
"value": false
},
"ShippingBranch": {},
"ShippingContactSameAsMain": {
"value": false
},
"ShippingRule": {
"value": "Cancel Remainder"
},
"ShippingTerms": {},
"ShippingZoneID": {},
"ShipVia": {},
"StatementCycleID": {
"value": "ENDOFMONTH"
},
"StatementType": {
"value": "Open Item"
},
"Status": {
"value": "Active"
},
"TaxRegistrationID": {},
"TaxZone": {
"value": "RECEIVER"
},
"Terms": {
"value": "30D"
},
"WarehouseID": {},
"WriteOffLimit": {
"value": 0.0000
},
"custom": {},
"files": []
}]
If you're using Newtonsoft.Json then you can use JsonConvert.DeserializeObject and dynamic to get the results as a JObject. Then you can iterate over the results:
var results = JsonConvert.DeserializeObject<dynamic>(json);
foreach (var item in results)
{
Console.WriteLine(item.CustomerID);
}
Or, you can use LINQ to get only the CustomerIDs:
var customerIds = ((IEnumerable<dynamic>)results).Select(r => r.CustomerID);
foreach (var id in customerIds)
{
Console.WriteLine(id);
}
Try it online
I have some complex JSon that I am trying to parse into something meaningful. I'm attempting to deserialize using C# Json.net but I can't get the values that I need. What I need is the value from every ColData node except those in a "summary" section. I am able to deserialize into an object using but I am stuck there.
string pandltext = #"{
"Header": {
"Time": "2017-08-24T08:32:58-07:00",
"ReportName": "ProfitAndLoss",
"ReportBasis": "Accrual",
"StartPeriod": "2017-06-01",
"EndPeriod": "2017-06-30",
"SummarizeColumnsBy": "Total",
"Currency": "USD",
"Option": [
{
"Name": "AccountingStandard",
"Value": "GAAP"
},
{
"Name": "NoReportData",
"Value": "false"
}
]
},
"Columns": {
"Column": [
{
"ColTitle": "",
"ColType": "Account",
"MetaData": [
{
"Name": "ColKey",
"Value": "account"
}
]
},
{
"ColTitle": "Total",
"ColType": "Money",
"MetaData": [
{
"Name": "ColKey",
"Value": "total"
}
]
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "Income"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"value": "Design income",
"id": "82"
},
{
"value": "975.00"
}
],
"type": "Data"
},
{
"ColData": [
{
"value": "Discounts given",
"id": "86"
},
{
"value": "-30.50"
}
],
"type": "Data"
},
{
"Header": {
"ColData": [
{
"value": "Landscaping Services",
"id": "45"
},
{
"value": "360.00"
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "Job Materials",
"id": "46"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"value": "Fountains and Garden Lighting",
"id": "48"
},
{
"value": "550.00"
}
],
"type": "Data"
},
{
"ColData": [
{
"value": "Plants and Soil",
"id": "49"
},
{
"value": "1820.72"
}
],
"type": "Data"
},
{
"ColData": [
{
"value": "Sprinklers and Drip Systems",
"id": "50"
},
{
"value": "30.00"
}
],
"type": "Data"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total Job Materials"
},
{
"value": "2400.72"
}
]
},
"type": "Section"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total Landscaping Services"
},
{
"value": "2760.72"
}
]
},
"type": "Section"
},
{
"ColData": [
{
"value": "Pest Control Services",
"id": "54"
},
{
"value": "-100.00"
}
],
"type": "Data"
},
{
"ColData": [
{
"value": "Sales of Product Income",
"id": "79"
},
{
"value": "44.00"
}
],
"type": "Data"
},
{
"ColData": [
{
"value": "Services",
"id": "1"
},
{
"value": "400.00"
}
],
"type": "Data"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total Income"
},
{
"value": "4049.22"
}
]
},
"type": "Section",
"group": "Income"
},
{
"Summary": {
"ColData": [
{
"value": "Gross Profit"
},
{
"value": "4049.22"
}
]
},
"type": "Section",
"group": "GrossProfit"
},
{
"Header": {
"ColData": [
{
"value": "Expenses"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "Automobile",
"id": "55"
},
{
"value": "19.99"
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"value": "Fuel",
"id": "56"
},
{
"value": "179.15"
}
],
"type": "Data"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total Automobile"
},
{
"value": "199.14"
}
]
},
"type": "Section"
},
{
"Header": {
"ColData": [
{
"value": "Job Expenses",
"id": "58"
},
{
"value": "108.09"
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "Job Materials",
"id": "63"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"value": "Decks and Patios",
"id": "64"
},
{
"value": "88.09"
}
],
"type": "Data"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total Job Materials"
},
{
"value": "88.09"
}
]
},
"type": "Section"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total Job Expenses"
},
{
"value": "196.18"
}
]
},
"type": "Section"
},
{
"Header": {
"ColData": [
{
"value": "Legal & Professional Fees",
"id": "12"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"value": "Accounting",
"id": "69"
},
{
"value": "75.00"
}
],
"type": "Data"
},
{
"ColData": [
{
"value": "Lawyer",
"id": "71"
},
{
"value": "100.00"
}
],
"type": "Data"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total Legal & Professional Fees"
},
{
"value": "175.00"
}
]
},
"type": "Section"
},
{
"ColData": [
{
"value": "Maintenance and Repair",
"id": "72"
},
{
"value": "185.00"
}
],
"type": "Data"
},
{
"ColData": [
{
"value": "Meals and Entertainment",
"id": "13"
},
{
"value": "5.66"
}
],
"type": "Data"
},
{
"ColData": [
{
"value": "Rent or Lease",
"id": "17"
},
{
"value": "900.00"
}
],
"type": "Data"
},
{
"Header": {
"ColData": [
{
"value": "Utilities",
"id": "24"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"value": "Gas and Electric",
"id": "76"
},
{
"value": "114.09"
}
],
"type": "Data"
},
{
"ColData": [
{
"value": "Telephone",
"id": "77"
},
{
"value": "74.36"
}
],
"type": "Data"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total Utilities"
},
{
"value": "188.45"
}
]
},
"type": "Section"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total Expenses"
},
{
"value": "1849.43"
}
]
},
"type": "Section",
"group": "Expenses"
},
{
"Summary": {
"ColData": [
{
"value": "Net Operating Income"
},
{
"value": "2199.79"
}
]
},
"type": "Section",
"group": "NetOperatingIncome"
},
{
"Header": {
"ColData": [
{
"value": "Other Expenses"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"value": "Miscellaneous",
"id": "14"
},
{
"value": "916.00"
}
],
"type": "Data"
}
]
},
"Summary": {
"ColData": [
{
"value": "Total Other Expenses"
},
{
"value": "916.00"
}
]
},
"type": "Section",
"group": "OtherExpenses"
},
{
"Summary": {
"ColData": [
{
"value": "Net Other Income"
},
{
"value": "-916.00"
}
]
},
"type": "Section",
"group": "NetOtherIncome"
},
{
"Summary": {
"ColData": [
{
"value": "Net Income"
},
{
"value": "1283.79"
}
]
},
"type": "Section",
"group": "NetIncome"
}
]
}
}
// Deserialize to object
var rootObj = JsonConvert.DeserializeObject<ProfitLoss.Rootobject>( pandltext );
I've tried querying a JContainer like is mentioned in this post. I've tried deserlializing a fragment like is mentioned in the documentation and I've tried using linq as mentioned here in the documentation. So far all of my efforts have met varying degrees of "success" but none have yielded the values I'm trying to get. Eventually this data will be bound to a WPF DataGrid for viewing.
Edit:
Added entire Json file
These are a couple attempts to get something, but I run into null values in both cases.
// This always returns null
var results2 = doc.Descendants()
.OfType<JObject>()
.Where( x => x[ "value" ] != null );
// This gives me a null exception error
var doc1 = ( JContainer ) o[ "Rows" ];
foreach ( var row in rootObj.Rows.Row )
{
// Get a null exception
foreach ( var row2 in row.Rows.Row )
{
Console.WriteLine( row2.ToString() );
}
}
Edit 2:
Using what #Eser gave as a starting point, I am able to get a list of values, but unfortunately it's just a list of values. Instead of getting something like
"Design income", "975.00"
"Discounts given", "-30.50"
I get
"Design income"
"975"
"Discounts given"
"-30.50"
Here is the code I'm using to get a list of values:
var jObj = JObject.Parse( pandltext );
var results = jObj.SelectTokens( "$..Rows.Row[?(#.type == 'Data')]..value" ).ToList();
var jObj = JObject.Parse(json);
var colData = jObj.SelectTokens("$..ColData")
.Except(jObj.SelectTokens("$..Summary.ColData"))
.ToList();
EDIT
foreach(var item in colData)
{
Console.WriteLine(string.Join("=", item.Select(x => x["value"])));
}
or
var finalList = colData.Select(item => item.Select(x => (string)x["value"]).ToList())
.ToList();
public class Option
{
public string Name { get; set; }
public string Value { get; set; }
}
public class Header
{
public DateTime Time { get; set; }
public string ReportName { get; set; }
public string ReportBasis { get; set; }
public string StartPeriod { get; set; }
public string EndPeriod { get; set; }
public string SummarizeColumnsBy { get; set; }
public string Currency { get; set; }
public IList<Option> Option { get; set; }
}
public class MetaData
{
public string Name { get; set; }
public string Value { get; set; }
}
public class Column
{
public string ColTitle { get; set; }
public string ColType { get; set; }
public IList<MetaData> MetaData { get; set; }
}
public class Columns
{
public IList<Column> Column { get; set; }
}
public class ColData
{
public string value { get; set; }
public string id { get; set; }
}
public class ColData
{
public string value { get; set; }
public string id { get; set; }
}
public class Row
{
public IList<ColData> ColData { get; set; }
public string type { get; set; }
}
public class Rows
{
public IList<Row> Row { get; set; }
}
public class ColData
{
public string value { get; set; }
}
public class Summary
{
public IList<ColData> ColData { get; set; }
}
public class ColData
{
public string value { get; set; }
public string id { get; set; }
}
public class Row
{
public Header { get; set; }
public Rows Rows { get; set; }
public Summary Summary { get; set; }
public string type { get; set; }
public IList<ColData> ColData { get; set; }
}
public class Rows
{
public IList<Row> Row { get; set; }
}
public class Row
{
public IList<ColData> ColData { get; set; }
public string type { get; set; }
public Header { get; set; }
public Rows Rows { get; set; }
public Summary { get; set; }
}
public class Rows
{
public IList<Row> Row { get; set; }
}
public class Row
{
public Header { get; set; }
public Rows Rows { get; set; }
public Summary { get; set; }
public string type { get; set; }
public string group { get; set; }
}
public class Rows
{
public IList<Row> Row { get; set; }
}
public class Example
{
public Header Header { get; set; }
public Columns Columns { get; set; }
public Rows Rows { get; set; }
}
and use it with :
Example results = Newtonsoft.JSON.JsonConvert.DeserializeObject<Example>(json);
I receive the following JSON string. It is part of the specifications of products. The data represents the Header ("General") and the items within in Key value pairs.
I dont want to hard code any properties such as general, Display Features and should be able to
Retrieve the Header
Iterate on the key value pair.
So Far I have the following code
foreach (var SpecList in objAPIProduct.categorySpecificInfoV1.specificationList)
{
foreach(dynamic SpecItem in SpecList.General)
{
Console.WriteLine(SpecItem.key);
Console.WriteLine(SpecItem.value[0]);
}
}
I want to get rid of the "General" Property that I have hardcoded in the inner foreach loop and make the loop generic for all properties.
Here is the Json that I have
{
"General": [{
"key": "Sales Package",
"value": ["Laptop, Power Adapter, Warranty Document"]
},
{
"key": "Model Number",
"value": ["3558"]
},
{
"key": "Part Number",
"value": ["Z565103UIN9"]
},
{
"key": "Model Name",
"value": ["Inspiron 15"]
},
{
"key": "Series",
"value": ["Inspiron"]
},
{
"key": "Color",
"value": ["Black"]
},
{
"key": "Type",
"value": ["Notebook"]
},
{
"key": "Suitable For",
"value": ["Everyday Use"]
},
{
"key": "Battery Backup",
"value": ["Upto 3.5 hours"]
},
{
"key": "Battery Cell",
"value": ["4 cell"]
}]
},
{
"Processor and Memory Features": [{
"key": "Processor Brand",
"value": ["Intel"]
},
{
"key": "Processor Name",
"value": ["Core i3"]
},
{
"key": "Graphic Processor",
"value": ["Intel HD Graphics 5500"]
},
{
"key": "SSD",
"value": ["No"]
},
{
"key": "RAM",
"value": ["4 GB"]
},
{
"key": "RAM Type",
"value": ["DDR3"]
},
{
"key": "HDD Capacity",
"value": ["500 GB"]
},
{
"key": "Processor Variant",
"value": ["5005U"]
},
{
"key": "Clock Speed",
"value": ["2 GHz"]
},
{
"key": "Memory Slots",
"value": ["1 Slot"]
},
{
"key": "Expandable Memory",
"value": ["Upto 4 GB"]
},
{
"key": "RAM Frequency",
"value": ["1600 MHz"]
},
{
"key": "Cache",
"value": ["3 MB"]
},
{
"key": "RPM",
"value": ["5400"]
}]
}
On site json2csharp.com you can generate classes for your JSON.
public class General
{
public string key { get; set; }
public List<string> value { get; set; }
}
public class RootObject
{
public List<General> General { get; set; }
}
And deserialize JSON to it using JSON.NET:
RootObject ro = JsonConvert.DeserializeObject<RootObject>(json);
And:
foreach(General g in ro.General)
{
string k = g.key;
}
Rewrite your SpecList class like this
public class SpecList : Dictionary<string, List<SpecItem>>
{
}
From then you will be able to access your general property like this
foreach (var SpecList in objAPIProduct.categorySpecificInfoV1.specificationList)
{
foreach(var key in SpecList.Keys)
{
foreach(var SpecItem in SpecList[key])
{
Console.WriteLine(SpecItem.key);
Console.WriteLine(SpecItem.value[0]);
}
}
}
Hope it helps.
After trying out a lot of options, I found that it is not possible to get the "Name" of the property when we use Json.Net or JavascriptSerialiser.
Finally, I used the help of this thread -
Deserialize JSON into C# dynamic object?
wherein the person has suggested using System.Web.Helpers and it works perfect in my case.
Here is my final code:
dynamic objAPIProduct= Json.Decode(json);
List<ProductSpecification> objProductSpecificationList = new List<ProductSpecification>();
ProductSpecification objProductSpecification;
foreach (var SpecListCategoryList in objAPIProduct.categorySpecificInfoV1.specificationList)
{
foreach (var SpecCategory in SpecListCategoryList)
{
DynamicJsonArray objListitems = SpecCategory.Value;
for (int i = 0; i < objListitems.Length; i++)
{
objProductSpecification = new ProductSpecification();
objProductSpecification.SpecificationHead = SpecCategory.Key;
objProductSpecification.SpecificationKey = objListitems[i].key;
objProductSpecification.SpecificationValue = objListitems[i].value[0];
objProductSpecificationList.Add(objProductSpecification);
}
}
}
I have following JSON:
{
"cap": [
{
"type": "test"
},
{
"type": "test1"
},
{
"type": "test2",
"bla": "tst"
}
]
}
I want every object that have single property to be one line formated
{ "type": "test" }
so the final JSON should be
{
"cap": [
{ "type": "test" },
{ "type": "test1" },
{
"type": "test2",
"bla": "tst"
}
]
}
How to do this in c#?