I have this JSON:
{
"query": {
"count": 43,
"created": "2016-03-12T09:46:36Z",
"lang": "en-US",
"results": {
"a": [
{
"class": "image",
"href": "/wiki/File:Yahoo!_logo.svg",
"img": {
"alt": "Yahoo! logo.svg",
"data-file-height": "233",
"data-file-width": "1000",
"height": "51",
"src": "//upload.wikimedia.org/wikipedia/commons/thumb/2/24/
Yahoo%21_logo.svg/220px-Yahoo%21_logo.svg.png",
"srcset": "//upload.wikimedia.org/wikipedia/commons/thumb/2/24/
Yahoo%21_logo.svg/330px-Yahoo%21_logo.svg.png 1.5x
, //upload.wikimedia.org/wikipedia/commons/thumb/2/24/
Yahoo%21_logo.svg/440px-Yahoo%21_logo.svg.png 2x",
"width": "220"
}
},
{
"href": "/wiki/Types_of_business_entity",
"title": "Types of business entity",
"content": "Type"
},
{
"href": "/wiki/Public_company",
"title": "Public company",
"content": "Public"
},
{
"href": "/wiki/Ticker_symbol",
"title": "Ticker symbol",
"content": "Traded as"
},
{
"href": "/wiki/NASDAQ",
"title": "NASDAQ",
"content": "NASDAQ"
},
{
"class": "external text",
"href": "http://www.nasdaq.com/symbol/yhoo",
"rel": "nofollow",
"content": "YHOO"
},
{
"href": "/wiki/NASDAQ-100",
"title": "NASDAQ-100",
"content": "NASDAQ-100 Component"
},
{
"class": "mw-redirect",
"href": "/wiki/S%26P_500",
"title": "S&P 500",
"content": "S&P 500 Component"
},
{
"href": "/wiki/Sunnyvale,_California",
"title": "Sunnyvale, California",
"content": "Sunnyvale"
},
{
"href": "/wiki/Entrepreneurship",
"title": "Entrepreneurship",
"content": "Founder(s)"
},
{
"href": "/wiki/Jerry_Yang_(entrepreneur)",
"title": "Jerry Yang (entrepreneur)",
"content": "Jerry Yang"
},
{
"href": "/wiki/David_Filo",
"title": "David Filo",
"content": "David Filo"
},
{
"href": "/wiki/Maynard_Webb",
"title": "Maynard Webb",
"content": "Maynard Webb"
},
{
"href": "/wiki/Marissa_Mayer",
"title": "Marissa Mayer",
"content": "Marissa Mayer"
},
{
"href": "/wiki/David_Filo",
"title": "David Filo",
"content": "David Filo"
},
{
"href": "#cite_note-1",
"span": [
"[",
"]"
],
"content": "1"
},
{
"href": "/wiki/Product_(business)",
"title": "Product (business)",
"content": "Products"
},
{
"class": "mw-redirect",
"href": "/wiki/Yahoo_News",
"title": "Yahoo News",
"content": "Yahoo News"
},
{
"class": "mw-redirect",
"href": "/wiki/Yahoo_Mail",
"title": "Yahoo Mail",
"content": "Yahoo Mail"
},
{
"class": "mw-redirect",
"href": "/wiki/Yahoo_Finance",
"title": "Yahoo Finance",
"content": "Yahoo Finance"
},
{
"class": "mw-redirect",
"href": "/wiki/Yahoo_Sports",
"title": "Yahoo Sports",
"content": "Yahoo Sports"
},
{
"class": "mw-redirect",
"href": "/wiki/Yahoo_Search",
"title": "Yahoo Search",
"content": "Yahoo Search"
},
{
"class": "mw-redirect",
"href": "/wiki/Yahoo_Messenger",
"title": "Yahoo Messenger",
"content": "Yahoo Messenger"
},
{
"href": "/wiki/Yahoo!_Answers",
"title": "Yahoo! Answers",
"content": "Yahoo! Answers"
},
{
"href": "/wiki/Tumblr",
"title": "Tumblr",
"content": "Tumblr"
},
{
"href": "/wiki/Flickr",
"title": "Flickr",
"content": "Flickr"
},
{
"href": "/wiki/List_of_Yahoo!-owned_sites_and_services",
"title": "List of Yahoo!-owned sites and services",
"content": "See Yahoo products"
},
{
"href": "/wiki/Revenue",
"title": "Revenue",
"content": "Revenue"
},
{
"href": "#cite_note-2",
"span": [
"[",
"]"
],
"content": "2"
},
{
"href": "/wiki/Earnings_before_interest_and_taxes",
"title": "Earnings before interest and taxes",
"content": "Operating income"
},
{
"href": "#cite_note-10K-3",
"span": [
"[",
"]"
],
"content": "3"
},
{
"href": "/wiki/Net_income",
"title": "Net income",
"content": "Net income"
},
{
"href": "#cite_note-4",
"span": [
"[",
"]"
],
"content": "4"
},
{
"href": "/wiki/Asset",
"title": "Asset",
"content": "Total assets"
},
{
"href": "#cite_note-5",
"span": [
"[",
"]"
],
"content": "5"
},
{
"href": "/wiki/Equity_(finance)",
"title": "Equity (finance)",
"content": "Total equity"
},
{
"href": "#cite_note-6",
"span": [
"[",
"]"
],
"content": "6"
},
{
"href": "#cite_note-7",
"span": [
"[",
"]"
],
"content": "7"
},
{
"class": "mw-redirect",
"href": "/wiki/List_of_acquisitions_by_Yahoo!",
"title": "List of acquisitions by Yahoo!",
"content": "Yahoo subsidiaries"
},
{
"class": "external text",
"href": "https://www.yahoo.com",
"rel": "nofollow",
"wbr": [
null,
null
],
"content": "www.yahoo.com"
},
{
"href": "/wiki/Alexa_Internet",
"title": "Alexa Internet",
"content": "Alexa"
},
{
"class": "external text",
"href": "//en.wikipedia.org/w/index.php?title=Yahoo!&action=edit",
"content": "[update]"
},
{
"href": "#cite_note-alexaranking-8",
"span": [
"[",
"]"
],
"content": "8"
}
]
}
}
}
...but I am unable to convert this into DataTable in .Net
I need to convert the response into DataSet.
following are my classes that i used while converting response.i know we easily convert the response in list but the problem arise when we convert the response into datatable or dataset any one who have any solution? i have tried to convert this into datatable
public class YahooImg
{
public string alt { get; set; }
[JsonProperty("data-file-height")]
public string data_file_height { get; set; }
[JsonProperty("data-file-width")]
public string data_file_width { get; set; }
public string height { get; set; }
public string src { get; set; }
public string srcset { get; set; }
public string width { get; set; }
}
public class YahooData
{
[JsonProperty("class")]
public string CLASS { get; set; }
public string href { get; set; }
[JsonProperty("Img")]
public YahooImg img { get; set; }
public string title { get; set; }
public string content { get; set; }
public string rel { get; set; }
public List<string> span { get; set; }
public List<object> wbr { get; set; }
}
public class YahooResults
{
[JsonProperty("A")]
public List<YahooData> a { get; set; }
}
public class YahooQuery
{
public int count { get; set; }
public string created { get; set; }
public string lang { get; set; }
[JsonProperty("Results")]
public YahooResults results { get; set; }
}
public class YahooAPIData
{
[JsonProperty("query")]
public YahooQuery Yahooquery { get; set; }
public YahooQuery GetYahooResult(string url)
{
var ds = new YahooAPIData();
if (!url.ToLower().Contains("yahoo"))
return ds.Yahooquery;
try
{
var wc = new WebClient();
wc.Headers.Add(HttpRequestHeader.Accept, "application/json");
var response = wc.DownloadString(url);
var dss = JsonConvert.DeserializeObject<YahooAPIData>(response);
}
catch (Exception exp)
{
var r = exp;
}
return ds.Yahooquery;
}
}
I am not sure what exactly you want to do as you have not posted and dataset structure in which you want to parse but, If you create following classes then, I think you can parse your JSON content in Query object model.
public class Query
{
int count;
datetime created;
string lang;
Result[] a;
}
public class Result
{
string _class;
string href;
Image img;
}
public class Image
{
string alt;
string data_file_height;
string data_file_width;
string height;
string src;
string srcset;
string width;
}
Related
I am looking for a script to find the value of $6383.12 for Accounts Receivable (A/R) in this code. There are several values I want to be able to find but I can't seem to figure out how to structure my code to find the values I need.
I have spent time looking through and testing various versions of arrays, ILIst<> and other suggestions but I can't seem to get the final result I am looking for. I can find a single value (for example "Savings") but I don't know how to get the $800 value.
The script I am using is:
var root = JToken.Parse(data);
IList<JToken> t = root.SelectTokens("$...ColData[?(#.value == 'Accounts Receivable (A/R)')]").ToList();
foreach (var item in t)
{
Response.Write(item.ToString() + "<br/><br/>");
}
This gives me the Accounts Receivable (A/R) value but not the dollar value associated with it.
Here is the JSON result I am trying to parse through:
{
"Header": {
"ReportName": "BalanceSheet",
"Option": [
{
"Name": "AccountingStandard",
"Value": "GAAP"
},
{
"Name": "NoReportData",
"Value": "false"
}
],
"DateMacro": "this calendar year-to-date",
"ReportBasis": "Accrual",
"StartPeriod": "2016-01-01",
"Currency": "USD",
"EndPeriod": "2016-10-31",
"Time": "2016-10-31T09:42:21-07:00",
"SummarizeColumnsBy": "Total"
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "ASSETS"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "Current Assets"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "Bank Accounts"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"id": "35",
"value": "Checking"
},
{
"value": "1350.55"
}
],
"type": "Data"
},
{
"ColData": [
{
"id": "36",
"value": "Savings"
},
{
"value": "800.00"
}
],
"type": "Data"
}
]
},
"type": "Section",
"group": "BankAccounts",
"Summary": {
"ColData": [
{
"value": "Total Bank Accounts"
},
{
"value": "2150.55"
}
]
}
},
{
"Header": {
"ColData": [
{
"value": "Accounts Receivable"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"id": "84",
"value": "Accounts Receivable (A/R)"
},
{
"value": "6383.12"
}
],
"type": "Data"
}
]
},
"type": "Section",
"group": "AR",
"Summary": {
"ColData": [
{
"value": "Total Accounts Receivable"
},
{
"value": "6383.12"
}
]
}
},
{
"Header": {
"ColData": [
{
"value": "Other current assets"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"id": "81",
"value": "Inventory Asset"
},
{
"value": "596.25"
}
],
"type": "Data"
},
{
"ColData": [
{
"id": "4",
"value": "Undeposited Funds"
},
{
"value": "2117.52"
}
],
"type": "Data"
}
]
},
"type": "Section",
"group": "OtherCurrentAssets",
"Summary": {
"ColData": [
{
"value": "Total Other current assets"
},
{
"value": "2713.77"
}
]
}
}
]
},
"type": "Section",
"group": "CurrentAssets",
"Summary": {
"ColData": [
{
"value": "Total Current Assets"
},
{
"value": "11247.44"
}
]
}
},
{
"Header": {
"ColData": [
{
"value": "Fixed Assets"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"id": "37",
"value": "Truck"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"id": "38",
"value": "Original Cost"
},
{
"value": "13495.00"
}
],
"type": "Data"
}
]
},
"type": "Section",
"Summary": {
"ColData": [
{
"value": "Total Truck"
},
{
"value": "13495.00"
}
]
}
}
]
},
"type": "Section",
"group": "FixedAssets",
"Summary": {
"ColData": [
{
"value": "Total Fixed Assets"
},
{
"value": "13495.00"
}
]
}
}
]
},
"type": "Section",
"group": "TotalAssets",
"Summary": {
"ColData": [
{
"value": "TOTAL ASSETS"
},
{
"value": "24742.44"
}
]
}
},
{
"Header": {
"ColData": [
{
"value": "LIABILITIES AND EQUITY"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "Liabilities"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "Current Liabilities"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"Header": {
"ColData": [
{
"value": "Accounts Payable"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"id": "33",
"value": "Accounts Payable (A/P)"
},
{
"value": "1984.17"
}
],
"type": "Data"
}
]
},
"type": "Section",
"group": "AP",
"Summary": {
"ColData": [
{
"value": "Total Accounts Payable"
},
{
"value": "1984.17"
}
]
}
},
{
"Header": {
"ColData": [
{
"value": "Credit Cards"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"id": "41",
"value": "Mastercard"
},
{
"value": "157.72"
}
],
"type": "Data"
}
]
},
"type": "Section",
"group": "CreditCards",
"Summary": {
"ColData": [
{
"value": "Total Credit Cards"
},
{
"value": "157.72"
}
]
}
},
{
"Header": {
"ColData": [
{
"value": "Other Current Liabilities"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"id": "89",
"value": "Arizona Dept. of Revenue Payable"
},
{
"value": "4.55"
}
],
"type": "Data"
},
{
"ColData": [
{
"id": "90",
"value": "Board of Equalization Payable"
},
{
"value": "401.98"
}
],
"type": "Data"
},
{
"ColData": [
{
"id": "43",
"value": "Loan Payable"
},
{
"value": "4000.00"
}
],
"type": "Data"
}
]
},
"type": "Section",
"group": "OtherCurrentLiabilities",
"Summary": {
"ColData": [
{
"value": "Total Other Current Liabilities"
},
{
"value": "4406.53"
}
]
}
}
]
},
"type": "Section",
"group": "CurrentLiabilities",
"Summary": {
"ColData": [
{
"value": "Total Current Liabilities"
},
{
"value": "6548.42"
}
]
}
},
{
"Header": {
"ColData": [
{
"value": "Long-Term Liabilities"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"id": "44",
"value": "Notes Payable"
},
{
"value": "25000.00"
}
],
"type": "Data"
}
]
},
"type": "Section",
"group": "LongTermLiabilities",
"Summary": {
"ColData": [
{
"value": "Total Long-Term Liabilities"
},
{
"value": "25000.00"
}
]
}
}
]
},
"type": "Section",
"group": "Liabilities",
"Summary": {
"ColData": [
{
"value": "Total Liabilities"
},
{
"value": "31548.42"
}
]
}
},
{
"Header": {
"ColData": [
{
"value": "Equity"
},
{
"value": ""
}
]
},
"Rows": {
"Row": [
{
"ColData": [
{
"id": "34",
"value": "Opening Balance Equity"
},
{
"value": "-9337.50"
}
],
"type": "Data"
},
{
"ColData": [
{
"id": "2",
"value": "Retained Earnings"
},
{
"value": "91.25"
}
],
"type": "Data"
},
{
"ColData": [
{
"value": "Net Income"
},
{
"value": "2440.27"
}
],
"type": "Data",
"group": "NetIncome"
}
]
},
"type": "Section",
"group": "Equity",
"Summary": {
"ColData": [
{
"value": "Total Equity"
},
{
"value": "-6805.98"
}
]
}
}
]
},
"type": "Section",
"group": "TotalLiabilitiesAndEquity",
"Summary": {
"ColData": [
{
"value": "TOTAL LIABILITIES AND EQUITY"
},
{
"value": "24742.44"
}
]
}
}
]
},
"Columns": {
"Column": [
{
"ColType": "Account",
"ColTitle": "",
"MetaData": [
{
"Name": "ColKey",
"Value": "account"
}
]
},
{
"ColType": "Money",
"ColTitle": "Total",
"MetaData": [
{
"Name": "ColKey",
"Value": "total"
}
]
}
]
}
}
You can try this,
var json = File.ReadAllText("json1.json");
var jToken = JToken.Parse(json);
var reader = jToken.CreateReader();
while (reader.Read())
{
var value = reader.Value;
if (value != null && value.ToString() == "Accounts Receivable (A/R)")
{
var test = jToken.SelectToken(reader.Path.Replace("[0].value", "[1].value"));
}
}
If it's not doable to write json path which selects proper tokens you could try using Parent property and Children method.
foreach (var item in t)
{
var valueToken = item.Parent.Children().ElementAt(1);
Response.Write(valueToken.ToString() + "<br/><br/>");
}
i have a Json file that contains some information i need elsewhere in my code but a lot of the information is irrelivant.
At the moment ive just put it into a dynamic object so i could check that it was all working:
var data = JsonConvert.DeserializeObject<dynamic>(response.Content);
How do i get the information i need out of the Json file and store them somewhere as variables.
All other tutorials where its stored in a class use the whole Json file and doesnt look like it would be useful in my case.
Here's the Json, i only really need the Stats section at the end of the file for what im doing
{
"data": {
"id": "",
"type": "player",
"children": [
{
"id": "legend_8",
"type": "legend",
"metadata": {
"legend_name": "Pathfinder",
"icon": "https://trackercdn.com/cdn/apex.tracker.gg/legends/pathfinder-tile.png",
"bgimage": "https://trackercdn.com/cdn/apex.tracker.gg/legends/pathfinder-concept-bg-small.jpg",
"is_active": true
},
"stats": [
{
"metadata": {
"key": "Kills",
"name": "Kills",
"categoryKey": "combat",
"categoryName": "Combat",
"isReversed": false
},
"value": 377.0,
"percentile": 21.0,
"displayValue": "377",
"displayRank": ""
},
{
"metadata": {
"key": "Finishers",
"name": "Finishers",
"categoryKey": "game",
"categoryName": "Game",
"isReversed": false
},
"value": 39.0,
"percentile": 0.2,
"rank": 886,
"displayValue": "39",
"displayRank": "886"
}
]
},
{
"id": "legend_5",
"type": "legend",
"metadata": {
"legend_name": "Bloodhound",
"icon": "https://trackercdn.com/cdn/apex.tracker.gg/legends/bloodhound-tile.png",
"bgimage": "https://trackercdn.com/cdn/apex.tracker.gg/legends/bloodhound-concept-bg-small.jpg",
"is_active": false
},
"stats": [
{
"metadata": {
"key": "Kills",
"name": "Kills",
"categoryKey": "combat",
"categoryName": "Combat",
"isReversed": false
},
"value": 235.0,
"percentile": 16.0,
"displayValue": "235",
"displayRank": ""
}
]
}
],
"metadata": {
"statsCategoryOrder": [
"combat",
"game",
"weapons"
],
"platformId": 2,
"platformUserHandle": "",
"accountId": "",
"cacheExpireDate": "11/10/2019 10:48:14 PM",
"level": 49,
"avatarUrl": "https://avatar-cdn.tracker.gg/api/avatar/2/",
"countryCode": null,
"collections": 36,
"activeLegend": 8
},
"stats": [
{
"metadata": {
"key": "Level",
"name": "Level",
"categoryKey": "combat",
"categoryName": "Combat",
"isReversed": false
},
"value": 49.0,
"percentile": 46.0,
"displayValue": "49",
"displayRank": ""
},
{
"metadata": {
"key": "Kills",
"name": "Kills",
"categoryKey": "combat",
"categoryName": "Combat",
"isReversed": false
},
"value": 612.0,
"percentile": 20.0,
"displayValue": "612",
"displayRank": ""
},
{
"metadata": {
"key": "Finishers",
"name": "Finishers",
"categoryKey": "game",
"categoryName": "Game",
"isReversed": false
},
"value": 39.0,
"percentile": 0.5,
"displayValue": "39",
"displayRank": ""
},
{
"metadata": {
"key": "RankScore",
"name": "Rank Score",
"categoryKey": "game",
"categoryName": "Game",
"isReversed": false
},
"value": 64.0,
"percentile": 21.0,
"displayValue": "64",
"displayRank": ""
}
]
}
}
You could create a data structure which has only the relevant properties. For example,
public class StatMetaData
{
public string key { get; set; }
public string name { get; set; }
public string categoryKey { get; set; }
public string categoryName { get; set; }
public bool isReversed { get; set; }
}
public class Stat
{
public StatMetaData metadata { get; set; }
public double value { get; set; }
public double percentile { get; set; }
public string displayValue { get; set; }
public string displayRank { get; set; }
}
public class Data
{
public List<Stat> stats { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
Now you could deserialize the json as the following to retrieve the stats sections
var result = JsonConvert.DeserializeObject<RootObject>(json).data.stats;
Greeting,
I am finding difficulty in parsing a JSON format file in c# having an array of highly nested objects which looks as follows
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0003",
"type": "donut",
"name": "Old Fashioned",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
]
I am looking for a solution like
"id", "type","name", "ppu" as private members of a class and "batters" and "topping" as dictionary members.
Kindly suggest me the better way in getting it parsed.
Thank you.
Following class structure will help you to parse JSON to C# object.
public class Batter
{
public string id { get; set; }
public string type { get; set; }
}
public class Batters
{
public List<Batter> batter { get; set; }
}
public class Topping
{
public string id { get; set; }
public string type { get; set; }
}
public class RootObject
{
public string id { get; set; }
public string type { get; set; }
public string name { get; set; }
public double ppu { get; set; }
public Batters batters { get; set; }
public List<Topping> topping { get; set; }
}
I wanted to get gmail contacts(email contacts actually), so I registered on google developer console and got the credentials, and using access token got the contacts. With scopes:
https://www.google.com/m8/feeds/ + https://www.googleapis.com/auth/contacts.readonly
and request uri as :
https://www.google.com/m8/feeds/contacts/default/full?alt=json
which gave me this json result:
{
"version": "1.0",
"encoding": "UTF-8",
"feed": {
"xmlns": "http://www.w3.org/2005/Atom",
"xmlns$openSearch": "http://a9.com/-/spec/opensearchrss/1.0/",
"xmlns$batch": "http://schemas.google.com/gdata/batch",
"xmlns$gd": "http://schemas.google.com/g/2005",
"xmlns$gContact": "http://schemas.google.com/contact/2008",
"id": {
"$t": "xxx#test.ai"
},
"updated": {
"$t": "2017-03-17T16:00:05.743Z"
},
"category": [
{
"scheme": "http://schemas.google.com/g/2005#kind",
"term": "http://schemas.google.com/contact/2008#contact"
}
],
"title": {
"type": "text",
"$t": "xxx's Contacts"
},
"link": [
{
"rel": "alternate",
"type": "text/html",
"href": "http://www.google.com/"
},
{
"rel": "http://schemas.google.com/g/2005#feed",
"type": "application/atom+xml",
"href": "https://www.google.com/m8/feeds/contacts/xxx%40test.ai/full"
},
{
"rel": "http://schemas.google.com/g/2005#post",
"type": "application/atom+xml",
"href": "https://www.google.com/m8/feeds/contacts/xxx%40test.ai/full"
},
{
"rel": "http://schemas.google.com/g/2005#batch",
"type": "application/atom+xml",
"href": "https://www.google.com/m8/feeds/contacts/xxx%40test.ai/full/batch"
},
{
"rel": "self",
"type": "application/atom+xml",
"href": "https://www.google.com/m8/feeds/contacts/xxx%40test.ai/full?alt=json&max-results=25"
},
{
"rel": "next",
"type": "application/atom+xml",
"href": "https://www.google.com/m8/feeds/contacts/xxx%40test.ai/full?alt=json&start-index=26&max-results=25"
}
],
"author": [
{
"name": {
"$t": "xxx"
},
"email": {
"$t": "xxx#test.ai"
}
}
],
"generator": {
"version": "1.0",
"uri": "http://www.google.com/m8/feeds",
"$t": "Contacts"
},
"openSearch$totalResults": {
"$t": "32"
},
"openSearch$startIndex": {
"$t": "1"
},
"openSearch$itemsPerPage": {
"$t": "25"
},
"entry": [
{
"id": {
"$t": "http://www.google.com/m8/feeds/contacts/xxx%40test.ai/base/ca1e0840ced5eb5"
},
"updated": {
"$t": "2017-03-13T10:27:43.365Z"
},
"category": [
{
"scheme": "http://schemas.google.com/g/2005#kind",
"term": "http://schemas.google.com/contact/2008#contact"
}
],
"title": {
"type": "text",
"$t": "Adam aaa"
},
"link": [
{
"rel": "http://schemas.google.com/contacts/2008/rel#edit-photo",
"type": "image/*",
"href": "https://www.google.com/m8/feeds/photos/media/xxx%40test.ai/ca1e0840ced5eb5/1B2M2Y8AsgTpgAmY7PhCfg"
},
{
"rel": "self",
"type": "application/atom+xml",
"href": "https://www.google.com/m8/feeds/contacts/xxx%40test.ai/full/ca1e0840ced5eb5"
},
{
"rel": "edit",
"type": "application/atom+xml",
"href": "https://www.google.com/m8/feeds/contacts/xxx%40test.ai/full/ca1e0840ced5eb5/1489400863365001"
}
],
"gd$email": [
{
"rel": "http://schemas.google.com/g/2005#other",
"address": "adam#test.ai",
"primary": "true"
}
]
},
{
"id": {
"$t": "http://www.google.com/m8/feeds/contacts/xxx%40test.ai/base/d06991a8a601600"
},
"updated": {
"$t": "2017-03-13T10:27:43.365Z"
},
"category": [
{
"scheme": "http://schemas.google.com/g/2005#kind",
"term": "http://schemas.google.com/contact/2008#contact"
}
],
"title": {
"type": "text",
"$t": "Bailey Bob"
},
"link": [
{
"rel": "http://schemas.google.com/contacts/2008/rel#edit-photo",
"type": "image/*",
"href": "https://www.google.com/m8/feeds/photos/media/xxx%40test.ai/d06991a8a601600/1B2M2Y8AsgTpgAmY7PhCfg"
},
{
"rel": "self",
"type": "application/atom+xml",
"href": "https://www.google.com/m8/feeds/contacts/xxx%40test.ai/full/d06991a8a601600"
},
{
"rel": "edit",
"type": "application/atom+xml",
"href": "https://www.google.com/m8/feeds/contacts/xxx%40test.ai/full/d06991a8a601600/1489400863365001"
}
],
"gd$email": [
{
"rel": "http://schemas.google.com/g/2005#other",
"address": "bailey#test.ai",
"primary": "true"
}
]
},
{
"id": {
"$t": "http://www.google.com/m8/feeds/contacts/xxx%40test.ai/base/e33f110891b26a2"
},
"updated": {
"$t": "2017-03-13T10:27:43.365Z"
},
"category": [
{
"scheme": "http://schemas.google.com/g/2005#kind",
"term": "http://schemas.google.com/contact/2008#contact"
}
],
"title": {
"type": "text",
"$t": "cathy Wales"
},
"link": [
{
"rel": "http://schemas.google.com/contacts/2008/rel#edit-photo",
"type": "image/*",
"href": "https://www.google.com/m8/feeds/photos/media/xxx%40test.ai/e33f110891b26a2/1B2M2Y8AsgTpgAmY7PhCfg"
},
{
"rel": "self",
"type": "application/atom+xml",
"href": "https://www.google.com/m8/feeds/contacts/xxx%40test.ai/full/e33f110891b26a2"
},
{
"rel": "edit",
"type": "application/atom+xml",
"href": "https://www.google.com/m8/feeds/contacts/xxx%40test.ai/full/e33f110891b26a2/1489400863365001"
}
],
"gd$email": [
{
"rel": "http://schemas.google.com/g/2005#other",
"address": "cathy#test.ai",
"primary": "true"
}
]
}
]
}
}
Either I need a better way to get the email contacts out of gmail or I need a way to deserialize this json to class, I tried to deserialize by converting this json to C# but proved unsuccessful.
Let me know what can be done.
Resolved my issue, at times when comes with instances like '$t' or something similar having '$' in it, which when converted into C# class results in invalid name. To resolve that, add dll reference 'Newtonsoft.Json' and create a class with using namespace as 'using Newtonsoft.Json' and in each property where name becomes invalid like below;
public string __invalid_name__$t { get; set; }
Add Json property attribute like below and change the name as per your liking:
[JsonProperty("$t")]
public string NameOfMyChoosing { get; set; }
I need to deserialize the this json returned from grogle maps api:
{
"destination_addresses": [
"Via Medaglie D'Oro, 10, 47121 Forlì FC, Italia",
"Via Torino, 20123 Milano, Italia",
"Via Guglielmo Marconi, 71, 40121 Bologna, Italia",
"Via Irnerio, 40126 Bologna, Italia"
],
"origin_addresses": [
"Via Medaglie D'Oro, 10, 47121 Forlì FC, Italia",
"Via Torino, 20123 Milano, Italia",
"Via Guglielmo Marconi, 71, 40121 Bologna, Italia",
"Via Irnerio, 40126 Bologna, Italia"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "1 m",
"value": 0
},
"duration": {
"text": "1 min",
"value": 0
},
"status": "OK"
},
{
"distance": {
"text": "286 km",
"value": 286281
},
"duration": {
"text": "2 ore 48 min",
"value": 10083
},
"status": "OK"
},
{
"distance": {
"text": "80,1 km",
"value": 80088
},
"duration": {
"text": "1 ora 3 min",
"value": 3789
},
"status": "OK"
},
{
"distance": {
"text": "77,6 km",
"value": 77594
},
"duration": {
"text": "57 min",
"value": 3422
},
"status": "OK"
}
]
},
{
"elements": [
{
"distance": {
"text": "288 km",
"value": 287811
},
"duration": {
"text": "2 ore 48 min",
"value": 10052
},
"status": "OK"
},
{
"distance": {
"text": "1 m",
"value": 0
},
"duration": {
"text": "1 min",
"value": 0
},
"status": "OK"
},
{
"distance": {
"text": "212 km",
"value": 212423
},
"duration": {
"text": "2 ore 8 min",
"value": 7664
},
"status": "OK"
},
{
"distance": {
"text": "218 km",
"value": 218219
},
"duration": {
"text": "2 ore 9 min",
"value": 7740
},
"status": "OK"
}
]
},
{
"elements": [
{
"distance": {
"text": "78,5 km",
"value": 78528
},
"duration": {
"text": "56 min",
"value": 3346
},
"status": "OK"
},
{
"distance": {
"text": "212 km",
"value": 212190
},
"duration": {
"text": "2 ore 5 min",
"value": 7519
},
"status": "OK"
},
{
"distance": {
"text": "1 m",
"value": 0
},
"duration": {
"text": "1 min",
"value": 0
},
"status": "OK"
},
{
"distance": {
"text": "2,0 km",
"value": 1979
},
"duration": {
"text": "5 min",
"value": 316
},
"status": "OK"
}
]
},
{
"elements": [
{
"distance": {
"text": "74,7 km",
"value": 74719
},
"duration": {
"text": "55 min",
"value": 3278
},
"status": "OK"
},
{
"distance": {
"text": "218 km",
"value": 217951
},
"duration": {
"text": "2 ore 9 min",
"value": 7712
},
"status": "OK"
},
{
"distance": {
"text": "3,8 km",
"value": 3782
},
"duration": {
"text": "11 min",
"value": 671
},
"status": "OK"
},
{
"distance": {
"text": "1 m",
"value": 0
},
"duration": {
"text": "1 min",
"value": 0
},
"status": "OK"
}
]
}
],
"status": "OK"
}
I need to create a Distance Matrix so I'm only interested in the "value" field inside "distance".
I've tried this approach:
DataSet data = JsonConvert.DeserializeObject<DataSet>(jsonResponse);
DataTable dataTab = data.Tables["Elements"];
foreach (DataRow elements in dataTab.Rows)
{
Console.WriteLine(elements["distance"]);
//Do something else here
}
But The JSonConvert returns "Additional text found in JSON string after finishing deserializing object."
You should deserialize to classes that match your data. You can generate these classes at http://json2csharp.com/.
// use like
var rootObj = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
foreach (var row in rootObj.rows)
{
foreach (var element in row.elements)
{
Console.WriteLine(element.distance.text);
}
}
// you might want to change the property names to .Net conventions
// use [JsonProperty] to let the serializer know the JSON names where needed
public class Distance
{
public string text { get; set; }
public int value { get; set; }
}
public class Duration
{
public string text { get; set; }
public int value { get; set; }
}
public class Element
{
public Distance distance { get; set; }
public Duration duration { get; set; }
public string status { get; set; }
}
public class Row
{
public List<Element> elements { get; set; }
}
public class RootObject
{
public List<string> destination_addresses { get; set; }
public List<string> origin_addresses { get; set; }
public List<Row> rows { get; set; }
public string status { get; set; }
}
I believe the issue is with the cast to 'DataSet' based on a similar question I found searching Stack Overflow.
Try this as I believe it would work (you may need to use 'rows' instead of 'Elements', but I believe the approach of using a JObject will resolve the primary issue of the 'additional text'.
JObject json = JsonConvert.DeserializeObject<JObject>(jsonResponse);
foreach (Dictionary<string, object> item in data["Elements"])
{
foreach (string val in item.Values) {
Console.WriteLine(val);
}
}
Using dynamic :
dynamic json = JsonConvert.DeserializeObject(jsonResponse);
var rowCount = json.rows.Count;
Func<dynamic, int> getElementCount = r => r.elements.Count;
var maxElements = Enumerable.Max(json.rows, getElementCount);
var matrix = new int?[rowCount, maxElements];
for(int i = 0; i < rowCount; i++)
{
var elements = json.rows[i].elements;
for(int j = 0; j < elements.Count; j++)
{
var element = elements[j];
matrix[i, j] = element.distance.value;
}
}