I am trying to generate the HMAC signature. This is for a validation with credit card company. Below is my code to generate the HMAC signature:
public string APISecurityKey(Identity postParameters)
{
String secretAccessKey = "secretkey";
string data = "message";
byte[] secretKey = Encoding.UTF8.GetBytes(secretAccessKey);
HMACSHA256 hmac = new HMACSHA256(secretKey);
hmac.Initialize();
byte[] bytes = Encoding.UTF8.GetBytes(data);
byte[] rawHmac = hmac.ComputeHash(bytes);
return Convert.ToBase64String(rawHmac);
}
They are asking me to substitute the message field with the JSON request (JSON supplied should have all carriage return newline sequences replaced with a space character). My object looks like so:
public class Identity
{
public List<Header> header { get; set; }
public string firstName { get; set; }
public string LastName { get; set; }
public string middleName { get; set; }
public string address { get; set; }
public string mothersName { get; set; }
public string DriversLic { get; set; }
public DateTime insertTime { get; set; }
public string Status { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public DateTime UpdatedOn { get; set; }
}
}
public class Header
{
public string tenantId { get; set; }
public string requestType { get; set; }
public string clientReferenceId { get; set; }
public string expRequestId { get; set; }
public string txnId { get; set; }
public string messageTime { get; set; }
public string options { get; set; }
}
The example given to me for the message is like this:
{"tenantId": "TENANT1","request Type": "Simulator","clientRefere
nceId": "Hunter + ProveID","expRequestId": "333","messageTim
e": "2016-08-04T22:13:07Z","options": {"workflow": "wf1","model
Type":"mt1","responseType":1,"Responses": {…}}}
I am not sure how to include tenantId, tenantId, expRequestId, options as part of my JSON message. I am very new to JSON. I have this partial code:
public static async Task createJSON( Identity postParameters)
{
var tmpRequest = new HttpRequestMessage();
tmpRequest.Content = new StringContent(JsonConvert.SerializeObject(postParameters));
tmpRequest.Content.Headers.Add("tenantId", "V123456");
tmpRequest.Content.Headers.Add("requestType", "PreciseIdOnly");
}
postParameters is my Identity object with values. How can I create that JSON that includes tenantId, tenantId, expRequestId and the object so that I can put that JSON value in the message of APISecurityKey method. Below is the test JSON file that I need to create:
{
"header": {
"tenantId": "V123456",
"requestType": "Precise",
"clientReferenceId": "11111111",
"RequestId": "",
"txnId": "",
"messageTime": "2020-05-28T00:00:02Z",
"options": {}
},
"payload": {
"control": [
{
"option": "SUBSCRIBER_PREAMBLE",
"value": "wer"
},
{
"option": "SUBSCRIBER_OPERATOR_INITIAL",
"value": "WS"
},
{
"option": "SUBSCRIBER_SUB_CODE",
"value": "1111111"
},
{
"option": "PID_USERNAME",
"value": "demo"
},
{
"option": "PID_PASSWORD",
"value": "password"
},
{
"option": "PRODUCT_OPTION",
"value": "11"
}
],
"contacts": [{
"id": "APPLICANT_CONTACT_ID_1",
"person": {
"typeOfPerson": "",
"personIdentifier": "",
"personDetails": {
"dateOfBirth": "1990-12-11",
"yearOfBirth": "",
"age": "",
"gender": "",
"noOfDependents": "",
"occupancyStatus": "",
"mothersMaidenName": "",
"spouseName": ""
},
"names": [{
"id": "",
"firstName": "Test1",
"middleNames": "D",
"surName": "Test2",
"nameSuffix": ""
}]
},
"addresses": [{
"id": "Main_Contact_Address_0",
"addressType": "CURRENT",
"poBoxNumber": "",
"street": "2312 Test Drve",
"street2": "",
"postTown": "test",
"postal": "49548",
"stateProvinceCode": "CA"
}],
"identityDocuments": [{
"documentNumber": "123456789",
"hashedDocumentNumber": "",
"documentType": "SSN"
}]
}]
}
}
I want to generate the same JSOn as the sample above in C# using the objects.
any help will be highly appreciated.
If you using Visual studio, you can create the JSON by going to Edit menu and paster JSON as class. This will create all the classes for you and then you can assign values to the classes by instantiating them
Related
I am try to create a wild card search feature.
I have a json response it contains the username. i have to search the user like te*, so it will display corresponding usernames.
LIke test1, test2
The below code i am using to get the response
var JSONResponse = await SendGraphRequest("/users/", null, null, HttpMethod.Get);
i have tried below code and trying to filter in graph only
i have try to filter in graph only
var JSON = await SendGraphRequest("/users/", $"$filter=startswith(givenname,'b')", null, HttpMethod.Get);
var graphUserResponse2 = JsonConvert.DeserializeObject<GraphUserResponseMapping>(JSON);
so instead of given name i want to try to filter using user name.
i am using newtonsoft to parse the json but it is difficult to get the username in list then then i will apply the wild card search. but the problem is how to get the username and store in a list?
The below is json response
{
"odata.metadata": "test",
"odata.nextLink":"test",
"value": [
{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"signInNames": [
{
"type": "emailAddress",
"value": "test1#gmail"
},
{
"type": "username",
"value": "Test1"
}
],
"personId": "1"
},
{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"signInNames": [
{
"type": "emailAddress",
"value": "test2#gmail.com"
},
{
"type": "username",
"value": "Test2"
}
],
"personId": "2"
}
]
}
TIA
Roger!
You can use a Class ex:
YourClassName.cs
code inside this class
public class SignInName
{
public string Type { get; set; }
public string Value { get; set; }
}
public class Value
{
[JsonProperty(PropertyName = "odata.type")]
public string OdataType { get; set; }
public string ObjectType { get; set; }
public List<SignInName> SignInNames { get; set; }
public string PersonId { get; set; }
}
public class YourClassName
{
[JsonProperty(PropertyName = "odata.metadata")]
public string OdataMetadata { get; set; }
[JsonProperty(PropertyName = "odata.nextLink")]
public string OdataNextLink { get; set; }
public List<Value> Value { get; set; }
}
So you can search for the usernames and put it into a list.
Ex:
List<string> userNameList = new List<string>();
var json = "{ \"odata.metadata\": \"test\", \"odata.nextLink\":\"test\", \"value\": [ { \"odata.type\": \"Microsoft.DirectoryServices.User\", \"objectType\": \"User\", \"signInNames\": [ { \"type\": \"emailAddress\", \"value\": \"test1#gmail\" }, { \"type\": \"username\", \"value\": \"Test1\" } ], \"personId\": \"1\" }, { \"odata.type\": \"Microsoft.DirectoryServices.User\", \"objectType\": \"User\", \"signInNames\": [ { \"type\": \"emailAddress\", \"value\": \"test2#gmail.com\" }, { \"type\": \"username\", \"value\": \"Test2\" } ], \"personId\": \"2\" } ] }";
var yourClassName = JsonConvert.DeserializeObject<YourClassName>(json);
foreach (var value in yourClassName.Value)
{
userNameList.AddRange(value.SignInNames.Where(x => x.Type == "username").Select(x => x.Value).ToList());
}
I'm completely new to JSON and need to be able to get a my JSON string converted into a DataTable.
Here is my JSON. I have changed about data for security reasons
[
{
"uuid": "af9fcfc7-61af-4484-aaa8-7dhcced2f2f79",
"call_start_time": 1551892096171,
"call_duration": 1150,
"created_on": "2019-03-06",
"cost": 0,
"call_type": "inbound",
"from": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 7*** ******"
},
"to": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 **** ******0"
},
"answered": true,
"answered_by": {
"uuid": "48bj949-e72e-4239-a337-e181a1b45841",
"type": "sipuser",
"name": "SipUser",
"nickname": "Myself",
"number": "1001"
},
"has_recording": true,
"call_route": "c30e45g0e-3da4-4a67-9a04-27e1d9d31129",
"is_fax": false
},
{
"uuid": "f62kmop2b-f929-4afc-8c05-a8c1bc43225d",
"call_start_time": 1551890795202,
"call_duration": 12,
"created_on": "2019-03-06",
"cost": 0.012,
"call_type": "outbound",
"from": {
"uuid": "68a50328-f5b0-4c5e-837c-667ea50878f3",
"type": "sipuser",
"name": "Spare",
"nickname": "Spare",
"number": "1011"
},
"to": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 *** *** ****"
},
"answered": true,
"answered_by": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 ***1*****0"
},
"has_recording": false,
"call_route": "",
"is_fax": false
},
{
"uuid": "b1b495c4-ecf6-44c0-8020-28c9eddc7afe",
"call_start_time": 1551890780607,
"call_duration": 10,
"created_on": "2019-03-06",
"cost": 0.012,
"call_type": "outbound",
"from": {
"uuid": "68a50328-f5b0-4c5e-837c-667ea50878f3",
"type": "sipuser",
"name": "Spare",
"nickname": "Spare",
"number": "1011"
},
"to": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 *** *** ****"
},
"answered": true,
"answered_by": {
"uuid": "",
"type": "number",
"name": "",
"nickname": "",
"number": "+44 *** *** ****"
},
"has_recording": false,
"call_route": "",
"is_fax": false
}
]
The way I want it presented needs to be similar to the way this website presents the datatable
https://konklone.io/json/
I've been all of the web now and am starting to run out of options. I did try looking into creating it with classes however that wasn't successful.
I have also tried all of the following examples (plus others)
https://www.code-sample.com/2017/04/convert-json-to-datatable-asp-net-c.html
Import Complex JSON file to C# dataTable
Convert JSON to DataTable
https://www.codeproject.com/Questions/590838/convertplusJSONplusstringplustoplusdatatable
Even if this goes into a DataSet and then I sort out the tables from there. Any help at all will be much appreciated.
Edit
I will explain why this is a little bit different from the assumed duplicate question located here
Convert JSON to DataTable
The answer to this question doesn't seem to be taking into account that I have nested JSON's that I need to get access to. I have tried it and I still do not get any of the from/number fields and the to/number fields.
I will admit that my question is a extention to this other duplicate question
Ok so here is the code to parse your JSON structure into a C# List. Once you have this list, you can convert it to a DataTable using the methods that you have researched. I have created a sample Data Table based on your JSON structure.
Your model would be:
public class JsonInfo
{
public string uuid { get; set; }
public string call_start_time { get; set; }
public string call_duration { get; set; }
public string created_on { get; set; }
public string cost { get; set; }
public string call_type { get; set; }
public string answered { get; set; }
public string has_recording { get; set; }
public string call_route { get; set; }
public string is_fax { get; set; }
public From from { get; set; }
public To to { get; set; }
public AnsweredBy answered_by { get; set; }
}
public class From
{
public string uuid { get; set; }
public string type { get; set; }
public string name { get; set; }
public string nickname { get; set; }
public string number { get; set; }
}
public class To
{
public string uuid { get; set; }
public string type { get; set; }
public string name { get; set; }
public string nickname { get; set; }
public string number { get; set; }
}
public class AnsweredBy
{
public string uuid { get; set; }
public string type { get; set; }
public string name { get; set; }
public string nickname { get; set; }
public string number { get; set; }
}
//Create a model to show your information
public class DisplayJsonInfo
{
public string uuid { get; set; }
public string call_start_time { get; set; }
public string call_duration { get; set; }
public string created_on { get; set; }
public string cost { get; set; }
public string from_uuid { get; set; }
public string from_type { get; set; }
public string from_name { get; set; }
public string from_nickname { get; set; }
}
To serialize your JSON into created Model and then create your DataTable:
var json = "[{\"uuid\":\"af9fcfc7-61af-4484-aaa8-7dhcced2f2f79\",\"call_start_time\":1551892096171,\"call_duration\":1150,\"created_on\":\"2019-03-06\",\"cost\":0,\"call_type\":\"inbound\",\"from\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 7*** ******\"},\"to\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 **** ******0\"},\"answered\":true,\"answered_by\":{\"uuid\":\"48bj949-e72e-4239-a337-e181a1b45841\",\"type\":\"sipuser\",\"name\":\"SipUser\",\"nickname\":\"Myself\",\"number\":\"1001\"},\"has_recording\":true,\"call_route\":\"c30e45g0e-3da4-4a67-9a04-27e1d9d31129\",\"is_fax\":false},{\"uuid\":\"f62kmop2b-f929-4afc-8c05-a8c1bc43225d\",\"call_start_time\":1551890795202,\"call_duration\":12,\"created_on\":\"2019-03-06\",\"cost\":0.012,\"call_type\":\"outbound\",\"from\":{\"uuid\":\"68a50328-f5b0-4c5e-837c-667ea50878f3\",\"type\":\"sipuser\",\"name\":\"Spare\",\"nickname\":\"Spare\",\"number\":\"1011\"},\"to\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 *** *** ****\"},\"answered\":true,\"answered_by\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 ***1*****0\"},\"has_recording\":false,\"call_route\":\"\",\"is_fax\":false},{\"uuid\":\"b1b495c4-ecf6-44c0-8020-28c9eddc7afe\",\"call_start_time\":1551890780607,\"call_duration\":10,\"created_on\":\"2019-03-06\",\"cost\":0.012,\"call_type\":\"outbound\",\"from\":{\"uuid\":\"68a50328-f5b0-4c5e-837c-667ea50878f3\",\"type\":\"sipuser\",\"name\":\"Spare\",\"nickname\":\"Spare\",\"number\":\"1011\"},\"to\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 *** *** ****\"},\"answered\":true,\"answered_by\":{\"uuid\":\"\",\"type\":\"number\",\"name\":\"\",\"nickname\":\"\",\"number\":\"+44 *** *** ****\"},\"has_recording\":false,\"call_route\":\"\",\"is_fax\":false}]";
var data = JsonConvert.DeserializeObject<List<JsonInfo>>(json);
//Call your helper method to convert
CreateDataTable cl = new CreateDataTable();
DataTable dt = new DataTable();
DisplayJsonInfo show = new DisplayJsonInfo();
List<DisplayJsonInfo> showInfo = new List<DisplayJsonInfo>();
foreach(var value in data)
{
showInfo.Add(new DisplayJsonInfo
{
call_duration = value.call_duration,
call_start_time = value.call_start_time,
cost = value.cost,
uuid = value.uuid,
created_on = value.created_on,
from_uuid = value.from.uuid,
from_name = value.from.name,
from_type = value.from.type,
from_nickname=value.from.nickname
});
}
dt = cl.ToDataTable(showInfo);
Once you have this use a helper extension like ToDataTable() as mentioned here: Convert JSON to DataTable
Edit:
So after parsing out the information and using this helper to convert your List to DataTable:
using System;
using System.Text;
using System.IO;
using System.Configuration;
using System.Data;
using System.Collections.Generic;
using System.ComponentModel;
public class CreateDataTable
{
public DataTable ToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
}
Your DataTable would look something like this:
Edit Description:
I have created a model only to show your required data into the DataTable. Since I have parsed the JSON data into my C# list, I can access the data shown in my code using foreach loop. Then I simply get the data what I required and then create my Data Table.
Cheers.
I got following json string from response from server that looks like this:
{
"resultCount": 2,
"results": [
{
"apartmentNo": "",
"city": "BEOGRAD",
"floor": "",
"houseNo": "99",
"houseNo2": "",
"phoneNo": "011\/000-0000",
"postalCode": "11000",
"region": "SOME REGION",
"street": "SOME STREET",
"firstName": "FNAME",
"lastName": "LNAME"
},
{
"apartmentNo": "",
"city": "BEOGRAD",
"floor": "",
"houseNo": "99",
"houseNo2": "",
"phoneNo": "011\/000-0000",
"postalCode": "11000",
"region": "SOME REGION",
"street": "SOME STREET",
"firstName": "FNAME",
"lastName": "LNAME"
}
]
}
As it can be seen, there is two results in json response that belongs to "result" and it is separated like {...first...},{...second...}. I already know how to handle only one result, but how should I handle two or more results like this json example?
I want to add this data to data grid view to show result to user.
My code to parse a single result is:
JObject o = JObject.Parse(responseText);
string ime = o["results"]["firstName"].ToString();
string prezime = o["results"]["lastName"].ToString();
string adresa = o["results"]["street"].ToString() + " " + o["results"]["houseNo"].ToString();
string mesto = o["results"]["city"].ToString();
string pbroj = o["results"]["postalCode"].ToString();
string tel = o["results"]["phoneNo"].ToString();
dataGridView1.Rows.Clear();
dataGridView1.Rows.Add(ime, prezime, adresa, mesto, pbroj, tel);
I also found a method around here to literate trought all childs using jtokens but there must be a better way of parsing these in etc. multiple arrays, I am using Newtonsoft.Json.
Thank you very much.
you can just use a POO/Models like the following
public class Result
{
public string apartmentNo { get; set; }
public string city { get; set; }
public string floor { get; set; }
public string houseNo { get; set; }
public string houseNo2 { get; set; }
public string phoneNo { get; set; }
public string postalCode { get; set; }
public string region { get; set; }
public string street { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
}
public class RootObject
{
public int resultCount { get; set; }
public List<Result> results { get; set; }
}
and parse it like this
var root = JsonConvert.DeserializeObject<RootObject>("your json here ");
I have a ASP MVC project that is accessing an API to get bank holiday dates: https://www.gov.uk/bank-holidays.json
When I parse the JSON however I am getting problems when I try to get down to the level of the 'events'. Currently I have:
var json = new WebClient().DownloadString("https://www.gov.uk/bank-holidays.json");
JavaScriptSerializer serializer = new JavaScriptSerializer();
var test = serializer.Deserialize<Dictionary<string, Dictionary<string, object>>>(json);
I can't seem to be able to cast the final object in this deserializer to anything meaningful. I have tried a variety of objects, lists, arrays etc but nothing seem to work. I only ever seem to be able to cast it to object.
Ideally I'd like the JSON to be parsed to a meaningful object such as:
public class BankHoliday
{
public DateTime Date { get; set; }
public string Title { get; set; }
public Country CountryCode { get; set; }
public string Notes { get; set; }
public bool Bunting { get; set; }
}
public enum Country
{
EnglandWales,
Scotland,
NorthernIreland
}
I thought this would be fairly simple but I have tried everything. I'm sure it's something simple that I am missing.
Thanks
Don't use JavaScriptSerializer better choice is JSON.NET
On site json2csharp.com you can generate classes from JSON:
public class Event
{
public string title { get; set; }
public string date { get; set; }
public string notes { get; set; }
public bool bunting { get; set; }
}
public class EnglandAndWales
{
public string division { get; set; }
public List<Event> events { get; set; }
}
public class Scotland
{
public string division { get; set; }
public List<Event> events { get; set; }
}
public class NorthernIreland
{
public string division { get; set; }
public List<Event> events { get; set; }
}
public class RootObject
{
[JsonProperty(PropertyName = "england-and-wales")]
public EnglandAndWales EnglandAndWales { get; set; }
public Scotland scotland { get; set; }
[JsonProperty(PropertyName = "northern-ireland")]
public NorthernIreland NorthernIreland { get; set; }
}
And then deserialise it with this way:
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(output);
EDIT
Added properties in RootObject to handele bad names.
Tested on simplified JSON:
{
"england-and-wales": {
"division": "england-and-wales",
"events": [{
"title": "New Year’s Day",
"date": "2012-01-02",
"notes": "Substitute day",
"bunting": true
},
{
"title": "Good Friday",
"date": "2012-04-06",
"notes": "",
"bunting": false
},
{
"title": "Boxing Day",
"date": "2017-12-26",
"notes": "",
"bunting": true
}]
},
"scotland": {
"division": "scotland",
"events": [{
"title": "2nd January",
"date": "2012-01-02",
"notes": "",
"bunting": true
},
{
"title": "New Year’s Day",
"date": "2012-01-03",
"notes": "Substitute day",
"bunting": true
},
{
"title": "Boxing Day",
"date": "2017-12-26",
"notes": "",
"bunting": true
}]
},
"northern-ireland": {
"division": "northern-ireland",
"events": [{
"title": "New Year’s Day",
"date": "2012-01-02",
"notes": "Substitute day",
"bunting": true
},
{
"title": "St Patrick’s Day",
"date": "2012-03-19",
"notes": "Substitute day",
"bunting": true
},
{
"title": "Boxing Day",
"date": "2017-12-26",
"notes": "",
"bunting": true
}]
}
}
I would greatly encourage you to use json.net lirary
I think you key problème here is that you need to use your type (BankHoliday) in the type definition:
Dictionary<string, <Dictionary<string, BankHoliday>>
Why not just use dynamic?
public IHttpActionResult BankHolidays()
{
var rawJson = string.Empty;
using (var webClient = new WebClient())
{
webClient.Encoding = Encoding.UTF8; // Expected Content-Type response is "application/json; charset=utf-8"
rawJson = webClient.DownloadString("https://www.gov.uk/bank-holidays.json");
}
dynamic json = JsonConvert.DeserializeObject<dynamic>(rawJson);
return Ok(json);
}
I have some stream data from that i want to retrieve
"estimatedResultCount":"399" from this below data
how to get 399 value from this approach
parsing the JSON -> responseData -> cursor -> estimatedResultCount will get you backing count.
{
"responseData": {
"results": [
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://www.homeocare.in/",
"url": "http://www.homeocare.in/",
"visibleUrl": "www.homeocare.in",
"cacheUrl": "http://www.google.com/search?q=cache:E7xF9dtFWgIJ:www.homeocare.in",
"title": "Homeopathy Clinics in Hyderabad - Homeopathy Treatment",
"titleNoFormatting": "Homeopathy Clinics in Hyderabad - Homeopathy Treatment",
"content": "Homeocare International - World Class Homeopathy Clinic in India provides \ninformation on causes, symptoms, and Homeopathy treatment of various \ndiseases."
},
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://www.homeocare.in/contactus.html",
"url": "http://www.homeocare.in/contactus.html",
"visibleUrl": "www.homeocare.in",
"cacheUrl": "http://www.google.com/search?q=cache:zrjNDKonZY0J:www.homeocare.in",
"title": "Homeocare International | Contact Us",
"titleNoFormatting": "Homeocare International | Contact Us",
"content": "To get best Homeopathy treatment Contact Homeocare International through \nphone or fill contact form. We have branches all over South India."
},
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://www.homeocare.in/testimonials.html",
"url": "http://www.homeocare.in/testimonials.html",
"visibleUrl": "www.homeocare.in",
"cacheUrl": "http://www.google.com/search?q=cache:oPJKzW6sHOkJ:www.homeocare.in",
"title": "Homeocare International Reviews / Testimonials",
"titleNoFormatting": "Homeocare International Reviews / Testimonials",
"content": "Homeocare International Reviews / Testimonials for Happy Patient. We pride \nourselves on excellent service, and our reviews show it!"
},
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://www.homeocare.in/arthritis.html",
"url": "http://www.homeocare.in/arthritis.html",
"visibleUrl": "www.homeocare.in",
"cacheUrl": "http://www.google.com/search?q=cache:gqHnM_Tg0hcJ:www.homeocare.in",
"title": "Homeopathy Treatment for Arthritis | Arthritis Treatment",
"titleNoFormatting": "Homeopathy Treatment for Arthritis | Arthritis Treatment",
"content": "Get Homeopathy Treatment for arthritis and rheumatoid arthritis at Homeocare \nInternational provides safe and effective remedies with no side effects."
}
],
"cursor": {
"resultCount": "399",
"pages": [
{
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
},
{
"start": "8",
"label": 3
},
{
"start": "12",
"label": 4
},
{
"start": "16",
"label": 5
},
{
"start": "20",
"label": 6
},
{
"start": "24",
"label": 7
},
{
"start": "28",
"label": 8
}
],
"estimatedResultCount": "399",
"currentPageIndex": 0,
"moreResultsUrl": "http://www.google.com/search?oe=utf8&ie=utf8&source=uds&start=0&hl=en&q=site:homeocare.in",
"searchResultTime": "0.09"
}
},
"responseDetails": null,
"responseStatus": 200
}
Code
string strurl = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site:homeocare.in";
StreamReader stream = objm.URLServerRequest(strurl);
string myResponse = stream.ReadToEnd();
public StreamReader URLServerRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
StreamReader stream = new StreamReader(request.GetResponse().GetResponseStream());
return stream;
}
You can generate the class here http://json2csharp.com/, it's very easy.
Given that you succesfully download the json string, here's the code as a console application. It uses json.net (https://www.nuget.org/packages/Newtonsoft.Json/7.0.1-beta2)
class Program
{
static void Main(string[] args)
{
var json = #".... json string....";
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(obj.responseData.cursor.estimatedResultCount)
;
Console.ReadLine();
}
}
public class Result
{
public string GsearchResultClass { get; set; }
public string unescapedUrl { get; set; }
public string url { get; set; }
public string visibleUrl { get; set; }
public string cacheUrl { get; set; }
public string title { get; set; }
public string titleNoFormatting { get; set; }
public string content { get; set; }
}
public class Page
{
public string start { get; set; }
public int label { get; set; }
}
public class Cursor
{
public string resultCount { get; set; }
public List<Page> pages { get; set; }
public string estimatedResultCount { get; set; }
public int currentPageIndex { get; set; }
public string moreResultsUrl { get; set; }
public string searchResultTime { get; set; }
}
public class ResponseData
{
public List<Result> results { get; set; }
public Cursor cursor { get; set; }
}
public class RootObject
{
public ResponseData responseData { get; set; }
public object responseDetails { get; set; }
public int responseStatus { get; set; }
}