parsing JSON format file in c# - c#

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

Related

I'm not able to convert IRestresponse to a object. What am i missing?

I hope someone can help me out here, because I'm pretty stuck ;)
I do not understand the error I'm getting:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'OdosTest.OdosRecord' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Isn't my json respone (see in the bottom) okay?
I'm trying to deserialize my IRestResponse to a object, but with no luck. The classes should be finde, or where am I wrong?
Here is my code:
using System;
using RestSharp;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace OdosTest
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://triscan.odosolutions.com/api/v1/streams");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic HIDDEN");
IRestResponse response = client.Execute(request);
var odosRecord = JsonConvert.DeserializeObject<OdosRecord>(response.Content);
//Console.WriteLine(response.Content);
}
}
public class OdosRecord
{
public int version { get; set; }
public string id { get; set; }
public int loggerImei { get; set; }
public string vin { get; set; }
public DateTime startTime { get; set; }
public Signal[] signals { get; set; }
}
public class Signal
{
public string source { get; set; }
public string name { get; set; }
public string displayName { get; set; }
public string number { get; set; }
public string unit { get; set; }
public bool isNumericComplement { get; set; }
public Value[] values { get; set; }
}
public class Value
{
public DateTime timestamp { get; set; }
public string value { get; set; }
}
}
Here is the response I get:
[
{
"version": 1,
"id": "0414bafa-39fe-4924-a1e3-f2180161f058",
"loggerImei": 1000606,
"vin": "WF0VXXGCEVFY08396",
"startTime": "2020-07-03T12:59:04.000345Z",
"signals": [
{
"source": "OBD",
"name": "01_42_CMV",
"displayName": "CMV",
"number": "0142",
"unit": "V",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "13.78"
}
]
},
{
"source": "OBD",
"name": "DETECTED_PROTOCOL",
"displayName": "DETECTED_PROTOCOL",
"number": "N/A",
"unit": "",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "CAN"
}
]
},
{
"source": "OBD",
"name": "01_31_TravelledDistSinceCodeCleared",
"displayName": "TravelledDistSinceCodeCleared",
"number": "0131",
"unit": "km",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "53749"
}
]
}
]
}
]
Your json contains a List<OdosRecord>, so this should solve the issue:
var odosRecord = JsonConvert.DeserializeObject<List<OdosRecord>>(response.Content);
otherwise you cloud change your json to this (if you are able to change the contract):
{
"version": 1,
"id": "0414bafa-39fe-4924-a1e3-f2180161f058",
"loggerImei": 1000606,
"vin": "WF0VXXGCEVFY08396",
"startTime": "2020-07-03T12:59:04.000345Z",
"signals": [
{
"source": "OBD",
"name": "01_42_CMV",
"displayName": "CMV",
"number": "0142",
"unit": "V",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "13.78"
}
]
},
{
"source": "OBD",
"name": "DETECTED_PROTOCOL",
"displayName": "DETECTED_PROTOCOL",
"number": "N/A",
"unit": "",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "CAN"
}
]
},
{
"source": "OBD",
"name": "01_31_TravelledDistSinceCodeCleared",
"displayName": "TravelledDistSinceCodeCleared",
"number": "0131",
"unit": "km",
"isNumericComplement": false,
"values": [
{
"timestamp": "2020-07-03T12:59:04Z",
"value": "53749"
}
]
}
]
}

Read JSON output from AppInsights in C#

I want to read AppInsights API output in C# console application.
WebClient wc = new WebClient();
wc.BaseAddress = "https://api.applicationinsights.io/v1/apps/AppInsighID/query?query=requests|where timestamp>= ago(1h)|limit 100";
wc.Headers.Add("Host", "api.applicationinsights.io");
wc.Headers.Add("x-api-key", "key");
string json = wc.DownloadString("");
JObject jsonObject = JObject.Parse(json);
//With this, i got values for Rows
var rowsObject = jsonObject["tables"][0]["rows"];
Now values are in array, under rowObject, so how to read this?
I would also like to know the best practice we should follow when reading json string
I can see data like this
{
"tables": [
{
"name": "PrimaryResult",
"columns": [
{
"name": "timestamp",
"type": "datetime"
},
{
"name": "id",
"type": "string"
},
{
"name": "source",
"type": "string"
},
{
"name": "name",
"type": "string"
},
{
"name": "url",
"type": "string"
},
{
"name": "success",
"type": "string"
},
{
"name": "resultCode",
"type": "string"
},
{
"name": "duration",
"type": "real"
},
{
"name": "performanceBucket",
"type": "string"
},
{
"name": "itemType",
"type": "string"
},
{
"name": "customDimensions",
"type": "dynamic"
},
{
"name": "customMeasurements",
"type": "dynamic"
},
{
"name": "operation_Name",
"type": "string"
},
{
"name": "operation_Id",
"type": "string"
},
{
"name": "operation_ParentId",
"type": "string"
},
{
"name": "operation_SyntheticSource",
"type": "string"
},
{
"name": "session_Id",
"type": "string"
},
{
"name": "user_Id",
"type": "string"
},
{
"name": "user_AuthenticatedId",
"type": "string"
},
{
"name": "user_AccountId",
"type": "string"
},
{
"name": "application_Version",
"type": "string"
},
{
"name": "client_Type",
"type": "string"
},
{
"name": "client_Model",
"type": "string"
},
{
"name": "client_OS",
"type": "string"
},
{
"name": "client_IP",
"type": "string"
},
{
"name": "client_City",
"type": "string"
},
{
"name": "client_StateOrProvince",
"type": "string"
},
{
"name": "client_CountryOrRegion",
"type": "string"
},
{
"name": "client_Browser",
"type": "string"
},
{
"name": "cloud_RoleName",
"type": "string"
},
{
"name": "cloud_RoleInstance",
"type": "string"
},
{
"name": "appId",
"type": "string"
},
{
"name": "appName",
"type": "string"
},
{
"name": "iKey",
"type": "string"
},
{
"name": "sdkVersion",
"type": "string"
},
{
"name": "itemId",
"type": "string"
},
{
"name": "itemCount",
"type": "int"
}
],
"rows": [
[
"2020-01-16T07:07:35.8423912Z",
"ID",
"",
"POST ",
"https://",
"True",
"200",
57.679,
"<250ms",
"request",
"{\"Product Name\":\"Name\",\"Subscription Name\":\"Name\",\"Operation Name\":\"AdvancedSearch\",\"ApimanagementRegion\":\"Region\",\"ApimanagementServiceName\":\"Name\",\"Apim Request Id\":\"ID\",\"Request-Body\":\"{\\\"P1\\\":25,\\\"P2\\\":1,\\\"P3\\\":\\\"All \\\",\\\"P4\\\":\\\"Earliest\\\",\\\"P5\\\":\\\"Extended\\\",\\\"P6\\\":\\\"All \\\",\\\"P6\\\":\\\"Latest\\\",\\\"queryList\\\":[{\\\"P7\\\":\\\"physics\\\",\\\"P8\\\":\\\"A1\\\",\\\"operator\\\":\\\"\\\"}]}\",\"Cache\":\"None\",\"P9\":\"195.43.22.145\",\"API Name\":\"Name\",\"HTTP Method\":\"POST\"}",
"{\"Response Size\":776,\"Request Size\":1092,\"Client Time (in ms)\":0}",
"POST ",
"ID",
"ID",
"",
"",
"",
"1",
"",
"",
"PC",
"",
"",
"0.0.0.0",
"Milan",
"Milan",
"Italy",
"",
"Value1",
"Value2",
"ID1",
"AppInsight Name",
"Name",
"apim:0.12.885.0",
"ID",
1
]
]
}
]
}
You could deserialize the Json and fetch the Rows information. For example,
var result = JsonConvert.DeserializeObject<RootObject>(str);
var rowData = result.tables.SelectMany(x=>x.rows.SelectMany(c=>c));
If you do not want to Flatten the results, you could use
var rowData = result.tables.SelectMany(x=>x.rows.Select(c=>c));
Where RootObject is defined as
public class Column
{
public string name { get; set; }
public string type { get; set; }
}
public class Table
{
public string name { get; set; }
public List<Column> columns { get; set; }
public List<List<string>> rows { get; set; }
}
public class RootObject
{
public List<Table> tables { get; set; }
}
If you intend to eliminate empty values, you could filter them out using Linq
var rowData = result.tables.SelectMany(x=>x.rows.SelectMany(c=>c))
.Where(x=>!string.IsNullOrEmpty(x));
Or for non-Flatten results
var rowData = result.tables.SelectMany(x=>x.rows.Select(c=>c))
.Where(x=>!string.IsNullOrEmpty(x.ToString()));
Update
Based on comment, to retrieve the information and parse it to a Dto based on the position of values in array, you could do the following. The attribute could be used for handling inline Json Properties as well, as mentioned in the comment.
You could begin by defining an attribute as following.
public class DtoDefinitionAttribute:Attribute
{
public DtoDefinitionAttribute(int order)=>Order = order;
public DtoDefinitionAttribute(int order,bool isJson,Type jsonDataType)
{
Order = order;
JsonDataType = jsonDataType;
IsJson = isJson;
}
public bool IsJson{get;} = false;
public int Order{get;}
public Type JsonDataType {get;}
}
And, then you could decorate your Dto properties with the index of corresponding value in the array. Additionally, in case of Json string expected as Json, then you could use the attribute to indicate it as well, as shown in the ClientTime property For example,
public class Dto
{
[DtoDefinition(0)]
public DateTime CurrentDate{get;set;}
[DtoDefinition(1)]
public string ID{get;set;}
[DtoDefinition(2)]
public string Url{get;set;}
[DtoDefinition(11,true,typeof(Response))]
public Response Json1{get;set;}
}
public class Response
{
[JsonProperty("Response Size")]
public string ResponseSize{get;set;}
[JsonProperty("Request Size")]
public string RequestSize{get;set;}
[JsonProperty("Client Time (in ms)")]
public int ClientTime{get;set;}
}
Now you could use the rowData result obtained using
var listDto = new List<Dto>();
foreach(var row in rowData)
{
listDto.Add(AssignValues(row));
}
Where AssignValues are defined as
public Dto AssignValues(List<string> row)
{
var dto = new Dto();
var properties = typeof(Dto).GetProperties().Where(x=>x.GetCustomAttributes<DtoDefinitionAttribute>().Any());
foreach(var property in properties)
{
var attribute = property.GetCustomAttribute<DtoDefinitionAttribute>();
if(attribute.IsJson)
{
var jsonData = row[attribute.Order].ToString();
var deserializedData = JsonConvert.DeserializeObject(jsonData,attribute.JsonDataType);
property.SetValue(dto,deserializedData);
}
else
{
property.SetValue(dto,Convert.ChangeType(row[attribute.Order],property.PropertyType));
}
}
return dto;
}
The AssignValues method uses reflection to read the Attributes and create an instance of Dto based on it. In case, it finds the attribute defines it as Json, then it would deserialize the json value and use the result.
Demo Code

How to only deserialize part of a Json file into a class c#

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;

Normalise JSON for flexible WebAPI response

I have a WebAPI method that returns Json in a flexible structure that depends on the request.
Part of the problem is that there could be any number of columns, and they could be any type. The 2 given below (Code and Count) are just one example.
This structure is based on the underlying classes but there could be any number of columns in the output. So, rather than the usual properties you might expect, these are objects in a collection with Name and Value properties.
The downside of this flexible approach is that it gives a non-standard format.
Is there a way to transform this into a more normalised shape? Are there maybe some attributes I can add to the class properties to change the way they are serialised?
For example, where there are 2 columns - Code (string) and Count (numeric):
Current Json:
{
"Rows": [
{
"Columns": [
{
"Value": "1",
"Name": "Code"
},
{
"Value": 13,
"Name": "Count"
}
]
},
{
"Columns": [
{
"Value": "2",
"Name": "Code"
},
{
"Value": 12,
"Name": "Count"
}
]
},
{
"Columns": [
{
"Value": "9",
"Name": "Code"
},
{
"Value": 1,
"Name": "Count"
}
]
},
{
"Columns": [
{
"Value": "5",
"Name": "Code"
},
{
"Value": 2,
"Name": "Count"
}
]
}
]
}
Ideally I'd like to transform it to this:
{
"Rows": [
{
"Code": "1",
"Count": 13
},
{
"Code": "2",
"Count": 12
},
{
"Code": "9",
"Count": 1
},
{
"Code": "5",
"Count": 2
}
]
}
The controller method (C#)
public ReportResponse Get(ReportRequest request)
{
var result = ReportLogic.GetReport(request);
return result;
}
The output classes
public class ReportResponse
{
public List<ReportRow> Rows { get; set; }
public ReportResponse()
{
Rows = new List<ReportRow>();
}
}
public class ReportRow
{
public List<ReportColumn> Columns { get; set; }
public ReportRow()
{
Columns = new List<ReportColumn>();
}
}
public class ReportColumn<T> : ReportColumn
{
public T Value { get; set; }
public ReportColumn(string name)
{
Name = name;
}
}
public abstract class ReportColumn
{
public string Name { get; internal set; }
}
I think the easiest way would be to map your class to a dictionary before serializing. Something like:
var dictionaries = List<Dictionary<string, object>();
foreach(var column in rows.Columns)
{
dictionaries.Add(new Dictionary<string, object>{{column.Name, column.Value}});
}
Then serialize the dictionaries variable should do the trick.
If you're using the output in JavaScript, you could translate as follows:
var
data = {
"Rows": [
{
"Columns": [
{
"Value": "1",
"Name": "Code"
},
{
"Value": 13,
"Name": "Count"
}
]
},
{
"Columns": [
{
"Value": "2",
"Name": "Code"
},
{
"Value": 12,
"Name": "Count"
}
]
},
{
"Columns": [
{
"Value": "9",
"Name": "Code"
},
{
"Value": 1,
"Name": "Count"
}
]
},
{
"Columns": [
{
"Value": "5",
"Name": "Code"
},
{
"Value": 2,
"Name": "Count"
}
]
}
]
},
output = [
];
data.Rows.forEach(function (row)
{
var
newRow = {};
row.Columns.forEach(function (column)
{
newRow[column.Name] = column.Value;
});
output.push(newRow);
})
console.log(JSON.stringify(output));

Convert Hierarchical List into Datatable/dataSet

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

Categories

Resources