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
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}"
}
]
},
In the json response the property "data" is used as a List and in other places in the Json it is used as a string.. when its used in the List the property has some value when its using as a string the value is coming as null..
How to include both scenario here when I am deserialzing and serializing the json.. without running in to exception A member with the name 'data' already exists. Use the JsonPropertyAttribute to specify another name
public class Example
{
[JsonProperty("data", NullValueHandling = NullValueHandling.Ignore)]
public List<Datum> Data { get; set; }
[JsonProperty("data", NullValueHandling = NullValueHandling.Include)]
public string Data { get; set; }
}
Here is what I tried to use a private property but not able to resolve the issue
[JsonProperty("data", NullValueHandling = NullValueHandling.Ignore)]
public List<Datum> Data { get; set; }
[JsonProperty("data2", NullValueHandling = NullValueHandling.Include)]
private List<Datum> Data2 { set { Data = value; } }
Here is the Json
{
"adRoots": null,
"allowedTagTypes": [
0,
1,
4
],
"canEdit": true,
"filterConfigData": {
"config": [{
"extraData": null,
"id": "Endpoints.ID.SearchInProgress",
"title": "Search in Progress",
"type": 5
},
{
"data": null,
"extraData": null,
"id": "Endpoints.ID.Policies",
"source": {
"definition": "dbo",
"displayColumn": "Name",
"keyColumn": "Id",
"name": "Policies",
"type": 1
},
"title": "Policies",
"type": 3
},
{
"extraData": null,
"id": "Endpoints.ID.MACs",
"title": "MAC Addresses",
"type": 1
},
{
"data": [{
"name": "Endpoint Closed",
"value": 11
},
{
"name": "Endpoint Completed",
"value": 15
},
{
"name": "Endpoint Opened",
"value": 10
}
],
"extraData": null,
"id": "Endpoints.ID.ClientActivityState",
"source": {
"definition": "State",
"displayColumn": "Name",
"keyColumn": "Id",
"name": "ClientActivityState",
"type": 2
},
"title": "Client Activity State",
"type": 3
},
{
"data": [{
"name": "System Alarm",
"value": 3
},
{
"name": "System Audit",
"value": 2
}
],
"extraData": null,
"id": "Endpoints.ID.AceType",
"source": {
"definition": "AceType",
"displayColumn": "Name",
"keyColumn": "Id",
"name": "AceType",
"type": 2
},
"title": "ACL: ACE Type",
"type": 3
},
{
"extraData": null,
"id": "Endpoints.ID.AceWho",
"title": "ACL: Trustee",
"type": 1
},
{
"data": [{
"name": "Append Data",
"value": 4
},
{
"name": "Delete",
"value": 65536
},
{
"name": "Execute",
"value": 32
}
],
"extraData": null,
"id": "Endpoints.ID.AceRights",
"source": {
"definition": "AceRights",
"displayColumn": "Name",
"editor": "ViewModel",
"keyColumn": "Id",
"name": "AceRights",
"type": 2
},
"title": "ACL: Authorization",
"type": 3
},
{
"extraData": null,
"id": "Endpoints.ID.FilterTagName",
"title": "Tag Name",
"type": 1
},
{
"data": null,
"extraData": null,
"id": "Endpoints.ID.FilterTags",
"source": {
"definition": "dbo",
"displayColumn": "Name",
"keyColumn": "Id",
"name": "Tags",
"type": 1
},
"title": "Tags",
"type": 3
},
{
"extraData": null,
"id": "Endpoints.Name.EndpointName",
"title": "Endpoint Name",
"type": 1
},
{
"data": null,
"extraData": null,
"id": "Endpoints.Version.Version",
"title": "Endpoint Version",
"type": 1
},
{
"extraData": null,
"id": "Endpoints.Platform.Platform",
"title": "Endpoint Platform",
"type": 1
},
{
"data": [{
"name": "Desktop",
"value": 1
},
{
"name": "Server",
"value": 2
},
{
"name": "Unknown",
"value": 0
}
],
"extraData": null,
"id": "ELPlatformType",
"source": {
"displayColumn": "Name",
"keyColumn": "Id",
"name": "PlatformType",
"type": 2
},
"title": "Platform Type",
"type": 3
},
{
"extraData": null,
"id": "Endpoints.LastPoll.LastPoll",
"title": "Last Poll Time",
"type": 2
}
],
"pagedListItems": null
},
"forests": null,
"item": {
"disallowed": false,
"editPermissions": 0,
"endpointsCount": 0,
"filter": null,
"id": 404,
"ldapPaths": null,
"name": "tag",
"query": null,
"type": 0
}
}
I have some JSON and would like to remove a node from the JSON but move the nodes inside the removed node to its parent.
Here is the JSON I am starting with:
{
"Response": {
"Outcome": {
"KeyValueOfstringOutcomepQnxSKQu": [
{
"Key": "Icon",
"Value": {
"DataType": "System.String",
"Field": "Icon",
"Value": "O"
}
},
{
"Key": "IconDescription",
"Value": {
"DataType": "System.String",
"Field": "IconDescription",
"Value": "Old"
}
},
{
"Key": "IconLongDescription",
"Value": {
"DataType": "System.String",
"Field": "IconLongDescription",
"Value": "Older"
}
}
]
}
}
}
This is JSON I want to end up with. I need the KeyValueOfstringOutcomepQnxSKQu node removed, but its children must still be present in the JSON:
{
"Response": {
"Outcome": [
{
"Key": "Icon",
"Value": {
"DataType": "System.String",
"Field": "Icon",
"Value": "O"
}
},
{
"Key": "IconDescription",
"Value": {
"DataType": "System.String",
"Field": "IconDescription",
"Value": "Old"
}
},
{
"Key": "IconLongDescription",
"Value": {
"DataType": "System.String",
"Field": "IconLongDescription",
"Value": "Older"
}
}
]
}
}
I have tried to remove the node like this, but that is as far as I got:
JObject rss = JObject.Parse(Convert.ToString(jsonText));
var x = rss.Remove("KeyValueOfstringOutcomepQnxSKQu");
How can I move the children up?
You can do this using SelectToken and Replace:
JObject rss = JObject.Parse(jsonText);
rss.SelectToken("Response.Outcome")
.Replace(rss.SelectToken("Response.Outcome.KeyValueOfstringOutcomepQnxSKQu"));
jsonText = rss.ToString();
Fiddle: https://dotnetfiddle.net/L6XoAf
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 have a Visual Studio (C#) deployment package (.zip) that I have pushed up to my S3 storage.
I want to run my CloudFormation script and have it create an instance of an IIS server (I have the script for this) and then deploy the Visual Studio web site to it from the S3 storage.
I'm looking for an example of the temple json that would do that
I have a template that does something similar to what you are looking for. Below is a template that I use. It may be more than you need, because it has an auto scaling group, but it will get you started. Basically, you need the IAM user to interact with cloud formation. The script in the UserData starts cf-init, which does the stuff in the metadata section.
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Autoscaling for .net Web application.",
"Parameters": {
"InstanceType": {
"Description": "WebServer EC2 instance type",
"Type": "String",
"Default": "m1.small",
"AllowedValues": [
"t1.micro",
"m1.small",
"m1.medium",
"m1.large",
"m1.xlarge",
"m2.xlarge",
"m2.2xlarge",
"m2.4xlarge",
"c1.medium",
"c1.xlarge",
"cc1.4xlarge",
"cc2.8xlarge",
"cg1.4xlarge"
],
"ConstraintDescription": "Must be a valid EC2 instance type."
},
"IamInstanceProfile": {
"Description": "Name of IAM Profile that will be used by instances to access AWS Services",
"Type": "String",
"Default": "YourProfileName"
},
"KeyName": {
"Description": "The EC2 Key Pair to allow access to the instances",
"Default": "yourkeypair",
"Type": "String"
},
"SpotPriceBid": {
"Description": "Max bid price of spot instances",
"Type": "String",
"Default": ".06"
},
"DeployS3Bucket": {
"Description": "The S3 Bucket where deploy files are stored",
"Type": "String",
"Default": "ApplicationBucket"
},
"DeployWebS3Key": {
"Description": "The zip file that holds the website",
"Type": "String",
"Default": "Application.zip"
},
"DNSHostedZone": {
"Type": "String",
"Default": "example.com.",
"AllowedPattern": "^[\\w\\.]*\\.$",
"ConstraintDescription": "DNSDomain must end with '.'"
},
"DNSSubDomain": {
"Type": "String",
"Default": "yoursubdomain"
}
},
"Mappings": {
"RegionToAMIMap": {
"us-east-1": {
"AMI": "ami-1234567"
}
}
},
"Resources": {
"IAMUser": {
"Type": "AWS::IAM::User",
"Properties": {
"Path": "/",
"Policies": [{
"PolicyName": "webuser",
"PolicyDocument": {
"Statement": [{
"Sid": "Stmt1353842250430",
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::HelgaDogWeb*/*"
]
}, {
"Sid": "Stmt1353842327065",
"Action": [
"cloudformation:DescribeStackResource"
],
"Effect": "Allow",
"Resource": [
"*"
]
}
]
}
}
]
}
},
"IAMUserAccessKey": {
"Type": "AWS::IAM::AccessKey",
"Properties": {
"UserName": {
"Ref": "IAMUser"
}
}
},
"WebSecurityGroup": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupDescription": "Enable Access From Elastic Load Balancer.",
"SecurityGroupIngress": [{
"IpProtocol": "tcp",
"FromPort": "443",
"ToPort": "443",
"SourceSecurityGroupOwnerId": {
"Fn::GetAtt": [
"WebLoadBalancer",
"SourceSecurityGroup.OwnerAlias"
]
},
"SourceSecurityGroupName": {
"Fn::GetAtt": [
"WebLoadBalancer",
"SourceSecurityGroup.GroupName"
]
}
}, {
"IpProtocol": "tcp",
"FromPort": "80",
"ToPort": "80",
"SourceSecurityGroupOwnerId": {
"Fn::GetAtt": [
"WebLoadBalancer",
"SourceSecurityGroup.OwnerAlias"
]
},
"SourceSecurityGroupName": {
"Fn::GetAtt": [
"WebLoadBalancer",
"SourceSecurityGroup.GroupName"
]
}
}
]
}
},
"WebLoadBalancer": {
"Type": "AWS::ElasticLoadBalancing::LoadBalancer",
"Properties": {
"Listeners": [{
"InstancePort": "443",
"InstanceProtocol": "HTTPS",
"LoadBalancerPort": "443",
"Protocol": "HTTPS",
"SSLCertificateId": "arn:aws:iam::123456789101:server-certificate/example"
}
],
"AvailabilityZones": {
"Fn::GetAZs": ""
},
"HealthCheck": {
"HealthyThreshold": "3",
"Interval": "30",
"Target": "HTTP:80/healthcheck.aspx",
"Timeout": 8,
"UnhealthyThreshold": "2"
}
}
},
"WebAsSpotLaunchConfiguration": {
"Type": "AWS::AutoScaling::LaunchConfiguration",
"Metadata": {
"AWS::CloudFormation::Init": {
"config": {
"sources": {
"C:\\inetpub\\wwwroot": {
"Fn::Join": [
"/",
[
"http://s3.amazonaws.com", {
"Ref": "DeployS3Bucket"
}, {
"Ref": "DeployWebS3Key"
}
]
]
}
},
"commands": {
"1-set-appPool-identity": {
"command": "C:\\Windows\\System32\\inetsrv\\appcmd set config /section:applicationPools /[name='DefaultAppPool'].processModel.identityType:LocalSystem",
"waitAfterCompletion": "0"
},
"2-add-http-binding": {
"command": "C:\\Windows\\System32\\inetsrv\\appcmd set site /site.name:\"Default Web Site\" /+bindings.[protocol='http',bindingInformation='*:80:']",
"waitAfterCompletion": "0"
}
}
}
},
"AWS::CloudFormation::Authentication": {
"S3AccessCreds": {
"type": "S3",
"accessKeyId": {
"Ref": "IAMUserAccessKey"
},
"secretKey": {
"Fn::GetAtt": [
"IAMUserAccessKey",
"SecretAccessKey"
]
},
"buckets": [{
"Ref": "DeployS3Bucket"
}
]
}
}
},
"Properties": {
"KeyName": {
"Ref": "KeyName"
},
"ImageId": {
"Fn::FindInMap": [
"RegionToAMIMap", {
"Ref": "AWS::Region"
},
"AMI"
]
},
"IamInstanceProfile": {
"Ref": "IamInstanceProfile"
},
"SecurityGroups": [{
"Ref": "WebSecurityGroup"
}
],
"InstanceType": {
"Ref": "InstanceType"
},
"SpotPrice": {
"Ref": "SpotPriceBid"
},
"UserData": {
"Fn::Base64": {
"Fn::Join": [
"",
[
"<script>\n",
"\"C:\\Program Files (x86)\\Amazon\\cfn-bootstrap\\cfn-init.exe\" -v -s ", {
"Ref": "AWS::StackName"
},
" -r WebAsSpotLaunchConfiguration ",
" --access-key ", {
"Ref": "IAMUserAccessKey"
},
" --secret-key ", {
"Fn::GetAtt": [
"IAMUserAccessKey",
"SecretAccessKey"
]
},
"\n",
"</script>"
]
]
}
}
}
},
"WebAsSpotGroup": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AvailabilityZones": {
"Fn::GetAZs": ""
},
"HealthCheckGracePeriod": "120",
"HealthCheckType": "EC2",
"LaunchConfigurationName": {
"Ref": "WebAsSpotLaunchConfiguration"
},
"LoadBalancerNames": [{
"Ref": "WebLoadBalancer"
}
],
"MaxSize": "20",
"MinSize": "1",
"DesiredCapacity": "1"
}
},
"WebAsSpotScaleUpPolicy": {
"Type": "AWS::AutoScaling::ScalingPolicy",
"Properties": {
"AdjustmentType": "PercentChangeInCapacity",
"AutoScalingGroupName": {
"Ref": "WebAsSpotGroup"
},
"Cooldown": "420",
"ScalingAdjustment": "200"
}
},
"WebAsSpotScaleDownPolicy": {
"Type": "AWS::AutoScaling::ScalingPolicy",
"Properties": {
"AdjustmentType": "ChangeInCapacity",
"AutoScalingGroupName": {
"Ref": "WebAsSpotGroup"
},
"Cooldown": "60",
"ScalingAdjustment": "-1"
}
},
"WebAsSpotScaleUpAlarm": {
"Type": "AWS::CloudWatch::Alarm",
"Properties": {
"MetricName": "CPUUtilization",
"Namespace": "AWS/EC2",
"Statistic": "Average",
"Period": "60",
"EvaluationPeriods": "1",
"Threshold": "75",
"AlarmActions": [{
"Ref": "WebAsSpotScaleUpPolicy"
}
],
"Dimensions": [{
"Name": "AutoScalingGroupName",
"Value": {
"Ref": "WebAsSpotGroup"
}
}
],
"ComparisonOperator": "GreaterThanThreshold"
}
},
"WebAsSpotScaleDownAlarm": {
"Type": "AWS::CloudWatch::Alarm",
"Properties": {
"MetricName": "CPUUtilization",
"Namespace": "AWS/EC2",
"Statistic": "Average",
"Period": "60",
"EvaluationPeriods": "2",
"Threshold": "50",
"AlarmActions": [{
"Ref": "WebAsSpotScaleDownPolicy"
}
],
"Dimensions": [{
"Name": "AutoScalingGroupName",
"Value": {
"Ref": "WebAsSpotGroup"
}
}
],
"ComparisonOperator": "LessThanThreshold"
}
},
"DNSRecord": {
"Type": "AWS::Route53::RecordSet",
"Properties": {
"HostedZoneName": {
"Ref": "DNSHostedZone"
},
"Comment": "VPN Host. Created by Cloud Formation.",
"Name": {
"Fn::Join": [
".",
[{
"Ref": "DNSSubDomain"
}, {
"Ref": "DNSHostedZone"
}
]
]
},
"Type": "CNAME",
"TTL": "150",
"ResourceRecords": [{
"Fn::GetAtt": [
"WebLoadBalancer",
"CanonicalHostedZoneName"
]
}
]
},
"DependsOn": "WebLoadBalancer"
}
},
"Outputs": {}
}
I havent tried it myself, but this post, on the AWS site, Using Amazon CloudFront with ASP.NET Apps maybe somewhere to start.