I have following JSON String and i want to insert the values in SQL database using C#.
{
"request": {
"Target": "Affiliate",
"Format": "jsonp",
"Service": "Offers",
"Version": "2",
"NetworkId": "dotcominfoway",
"Method": "findAll",
"api_key": "4bf7ba7b1904716179c9284cbd",
"callback": "angular.callbacks._2",
"_ga": "GA1.2.894200611.1458193988"
},
"response": {
"status": 1,
"httpStatus": 200,
"data": {
"2204": {
"Offer": {
"id": "2204",
"name": "App Of the Day Android IN Incent",
"description": "STEP 1 : You can place your own logo/creative in the offer wall as you like or you can place our creative.\r\n\r\nSTEP 2: If user clicks it will redirect to the play store to any application which he/she haven’t downloaded before in their device.\r\n\r\nSTEP 3 : User have to install the application and open it.",
"require_approval": "1",
"require_terms_and_conditions": 0,
"terms_and_conditions": null,
"preview_url": "http://appfly.mobi/red/02b4ef54-144b-11e5-a076-0cc47a44dbaa/?alg=2",
"currency": null,
"default_payout": "0.20000",
"status": "active",
"expiration_date": "2016-06-17 03:59:59",
"payout_type": "cpa_flat",
"percent_payout": "100.00",
"featured": null,
"conversion_cap": "0",
"monthly_conversion_cap": "0",
"payout_cap": "0.00",
"monthly_payout_cap": "0.00",
"allow_website_links": "0",
"allow_direct_links": "0",
"show_custom_variables": "0",
"show_mail_list": "0",
"dne_list_id": "0",
"email_instructions": "0",
"email_instructions_from": "",
"email_instructions_subject": "",
"has_goals_enabled": "0",
"default_goal_name": "",
"use_target_rules": "0",
"is_expired": "0",
"dne_download_url": null,
"dne_unsubscribe_url": null,
"dne_third_party_list": false
}
},
"3669": {
"Offer": {
"id": "3669",
"name": "Cash On IN Incent CPR",
"description": "Automatic OTP",
"require_approval": "1",
"require_terms_and_conditions": 0,
"terms_and_conditions": null,
"preview_url": "https://play.google.com/store/apps/details?id=com.softn",
"currency": "INR",
"default_payout": "12.00000",
"status": "active",
"expiration_date": "2016-09-29 03:59:59",
"payout_type": "cpa_flat",
"percent_payout": null,
"featured": null,
"conversion_cap": "1000",
"monthly_conversion_cap": "0",
"payout_cap": "0.00",
"monthly_payout_cap": "0.00",
"allow_website_links": "0",
"allow_direct_links": "0",
"show_custom_variables": "0",
"show_mail_list": "0",
"dne_list_id": "0",
"email_instructions": "0",
"email_instructions_from": "",
"email_instructions_subject": "",
"has_goals_enabled": "0",
"default_goal_name": "",
"use_target_rules": "0",
"is_expired": "0",
"dne_download_url": null,
"dne_unsubscribe_url": null,
"dne_third_party_list": false
}
}
....... and so on
I have written following code to insert into Dataset but it is giving error.
string url = "http:api.offers.com/Apiv3/json?NetworkId=inf&Target=Affiliate_Offer&Method=findAll&api_key=4bf7ba7b1904716179c9284cbd7db17018b8a5f";
string JsonString = new WebClient().DownloadString(url);
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(JsonString);
DataTable dataTable = dataSet.Tables["request"];
Console.WriteLine(dataTable.Rows.Count);
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["Target"] + " - " + row["Format"]);
}
Error Getting:
information: Unexpected JSON token when reading DataTable. Expected
StartArray, got StartObject. Path 'request', line 1, position 12.
So, please help me to convert the Json into Dataset and then insert into SQL database or direct to SQL database.
I'm currently using newtonsoft.json.
Other easy options are also welcome for my purpose.
The deserializer does not know what to do with the type DataSet.
Look at this answer: https://stackoverflow.com/a/11982180/1235106
Related
I have a JSON object like in below.
{
"?xml": {
"#version": "1.0",
"#encoding": "UTF-8"
},
"?xml-stylesheet": "type=\"text/xsl\" href=\"isokur.xsl\"",
"Tarih_Date": {
"#Tarih": "14.10.2022",
"#Date": "10/14/2022",
"#Bulten_No": "2022/196",
"Currency": [
{
"#CrossOrder": "0",
"#Kod": "USD",
"#CurrencyCode": "USD",
"Unit": "1",
"Isim": "ABD DOLARI",
"CurrencyName": "US DOLLAR",
"ForexBuying": "18.5596",
"ForexSelling": "18.5930",
"BanknoteBuying": "18.5466",
"BanknoteSelling": "18.6209",
"CrossRateUSD": null,
"CrossRateOther": null
},
{
"#CrossOrder": "1",
"#Kod": "AUD",
"#CurrencyCode": "AUD",
"Unit": "1",
"Isim": "AVUSTRALYA DOLARI",
"CurrencyName": "AUSTRALIAN DOLLAR",
"ForexBuying": "11.6732",
"ForexSelling": "11.7493",
"BanknoteBuying": "11.6195",
"BanknoteSelling": "11.8198",
"CrossRateUSD": "1.5862",
"CrossRateOther": null
}
]
}
}
And I want to grab only the this part from it. Where #CurrencyCode == "USD"
[
{
"#CrossOrder": "0",
"#Kod": "USD",
"#CurrencyCode": "USD",
"Unit": "1",
"Isim": "ABD DOLARI",
"CurrencyName": "US DOLLAR",
"ForexBuying": "18.5596",
"ForexSelling": "18.5930",
"BanknoteBuying": "18.5466",
"BanknoteSelling": "18.6209",
"CrossRateUSD": null,
"CrossRateOther": null
}
]
For this purpose, I created the code below according to this answer.
string result = JObject.Parse(json)["Tarih_Date"].SelectToken("$.Currency[?(#.#CurrencyCode=='USD')]")["Currency"].ToString();
But I couldn't make it word and I get the exception below. As I understand, my query doesn't find it's way(?) But couldn't understand where it is.
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Anything helps!
You get the exception because there is no property called Currency in the output of SelectToken. You will get the desired output by switching to:
var result = JObject.Parse(json)["Tarih_Date"].SelectToken("$.Currency[?(#.#CurrencyCode == 'USD')]");
This is my first post.
I am trying to integrate Shippo to our application and wish to obtain a specific value out of a Json response.
I am getting the following Json response:
{
"count": 3,
"next": null,
"previous": null,
"results": [
{
"object_created": "2019-08-28T12:58:57.064Z",
"object_id": "16b602e0ajdsk87c4313920bc5e3174XYZ",
"object_owner": "some#email.com",
"shipment": "bd62234e151244dab2b2152fdcd15e76",
"attributes": [
"FASTEST"
],
"amount": "31.30",
"currency": "USD",
"amount_local": "31.30",
"currency_local": "USD",
"provider": "USPS",
"provider_image_75": "https://shippo-static.s3.amazonaws.com/providers/75/USPS.png",
"provider_image_200": "https://shippo-static.s3.amazonaws.com/providers/200/USPS.png",
"servicelevel": {
"name": "Priority Mail Express",
"token": "usps_priority_express",
"terms": ""
},
"estimated_days": 1,
"arrives_by": null,
"duration_terms": "Overnight delivery to most U.S. locations.",
"messages": [],
"carrier_account": "4e1506b8b7f7449e90620967e45aa1e9",
"test": false,
"zone": "4"
},
{
"object_created": "2019-08-28T12:58:57.063Z",
"object_id": "ebdee42047aa49a3b7e08b1903ea02ea",
"object_owner": "some#email.com",
"shipment": "bd62234e151244dab2b2152fdcd15e76",
"attributes": [
"BESTVALUE",
"CHEAPEST"
],
"amount": "7.49",
"currency": "USD",
"amount_local": "7.49",
"currency_local": "USD",
"provider": "USPS",
"provider_image_75": "https://shippo-static.s3.amazonaws.com/providers/75/USPS.png",
"provider_image_200": "https://shippo-static.s3.amazonaws.com/providers/200/USPS.png",
"servicelevel": {
"name": "Priority Mail",
"token": "usps_priority",
"terms": ""
},
"estimated_days": 2,
"arrives_by": null,
"duration_terms": "Delivery within 1, 2, or 3 days based on where your package started and where it’s being sent.",
"messages": [],
"carrier_account": "4e1506b8b7f7449e90620967e45aa1e9",
"test": false,
"zone": "4"
},
{
"object_created": "2019-08-28T12:58:57.062Z",
"object_id": "ad410a41c84940ee80eb30c41c507613",
"object_owner": "some#email.com",
"shipment": "bd62234e151244dab2b2152fdcd15e76",
"attributes": [],
"amount": "7.78",
"currency": "USD",
"amount_local": "7.78",
"currency_local": "USD",
"provider": "USPS",
"provider_image_75": "https://shippo-static.s3.amazonaws.com/providers/75/USPS.png",
"provider_image_200": "https://shippo-static.s3.amazonaws.com/providers/200/USPS.png",
"servicelevel": {
"name": "Parcel Select",
"token": "usps_parcel_select",
"terms": ""
},
"estimated_days": 7,
"arrives_by": null,
"duration_terms": "Delivery in 2 to 8 days.",
"messages": [],
"carrier_account": "4e1506b8b7f7449e90620967e45aa1e9",
"test": false,
"zone": "4"
}
]
}
I am using this call:
WebClient webClient = new WebClient();
webClient.Headers.Add("Authorization: ShippoToken " + authToken);
var result = JsonValue.Parse(webClient.DownloadString("https://api.goshippo.com/shipments/"+ theObject.ObjectId + "/rates/USD"));
My question is how could I get just the "amount" value from the response?
Thank you for any help!
Instead of recreating the json layout as a class model you can work with Newtonsofts JToken. Which will leave you with less boilerplate code to create:
var json = "your json data";
// Parse the whole json string
var obj = JObject.Parse(json);
// Extract the results data as JArray
var results = (JArray)obj["results"];
// Iterate over all array entries and get the amount property
foreach(var result in results)
{
var amount = result["amount"].ToString();
// Do something with the amount
}
You could create some classes based on json then deserialize using JsonConvert
e.g https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
tip:
Copy the json and put in json viewer like https://jsonformatter.curiousconcept.com/
Use https://www.newtonsoft.com/json to deserialize the json response. If you didn't want that you could use a series of string.Split()'s to get the amount. But using newtonsoft (via the nuget package manager) would be the easiest.
I am trying to update the particular field in the JSON response, however i am able to parse through the JSON, but i am unable to update the field values.
Parsed through the JSON response and tried using
Operands_parse.SelectToken("FieldValue").Replace("1234,5678");
But when replace is changing the format of the response which is not suppose to happen
JObject Operands_parse = (JObject)Operands[0];
Operands_parse.SelectToken("FieldValue").Replace("1234,5678");
Below is the JSON snippet:
"Predicate": {
"Field": null,
"FieldValue": null,
"FilterOperator": "Equals",
"Operands": [
{
"Field": {
"Name": "Participant.IsPrimary",
"Alias": "Participant Is Primary",
"ValueInput": "UserName",
"FieldType": "Boolean",
"SortProxyName": "IsPrimary",
"PrismFieldName": "IsPrimaryFA",
"PrismDisplayFieldName": null,
"FieldValue": null,
"IsCustom": false,
"DependentField": null,
"Disabled": false,
"PlannedForDeprecation": false
},
"FieldValue": [
"true"
]
Output:
"FieldValue":
"1234,
5678",
Expected:
"FieldValue": [
"1234",
"5678"
],
Things got worked after converting the speicfic field to the JArray from which i can upadte the values.
string[] CRs ;
CRs = new string[2] {"1234","5678"};
JObject Operands_parse = (JObject)Operands[0];
JToken FieldValue_t;
Operands_parse.TryGetValue("FieldValue", out FieldValue_t);
JArray item = (JArray)FieldValue_t;
/*Removed old values*/
item.RemoveAt(0);
item.RemoveAt(1);
/*Added New Values*/
item.Add(items_no[0]);
item.Add(items_no[1]);
`
"Predicate": {
"Field": null,
"FieldValue": null,
"FilterOperator": "Equals",
"Operands": [
{
"Field": {
"Name": "ChangeRequestParticipant.IsPrimary",
"Alias": "Participant Is Primary",
"ValueInput": "UserName",
"FieldType": "Boolean",
"SortProxyName": "ChangeRequestParticipant.IsPrimary",
"PrismFieldName": "IsPrimaryFA",
"PrismDisplayFieldName": null,
"FieldValue": null,
"IsCustom": false,
"DependentField": null,
"Disabled": false,
"PlannedForDeprecation": false
},
"FieldValue": [
"1234",
"5678"
],`
Took reference from this link
Below is my JSON response. I want to fetch orderid, caseid each filed one by one and their value.
"cases": [
{
"status": "DISMISSED",
"createdAt": "2015-09-18T08:56:04+0000",
"investigationId": 19246020,
"caseId": 19246020,
"score": 794.6295793608853,
"adjustedScore": 794.6295793608853,
"updatedAt": "2015-09-18T08:56:05+0000",
"headline": "Steven Rusk",
"orderId": "116588",
"orderDate": "",
"orderAmount": 425.0,
"associatedTeam": {
"teamName": "B2C Jewels",
"teamId": 4289
},
"reviewDisposition": null,
"uuid": "5821ed91-5f8f-4b51-bd63-a8834f2a95b3"
},
{
"status": "DISMISSED",
"createdAt": "2015-09-16T11:33:28+0000",
"investigationId": 19114061,
"caseId": 19114061,
"score": 241.65405995385285,
"adjustedScore": 241.65405995385285,
"updatedAt": "2015-09-18T19:07:51+0000",
"headline": "221.134.83.50",
"orderId": "101",
"orderDate": "2015-09-16T17:07:30+0000",
"orderAmount": 9.99,
"associatedTeam": {
"teamName": "B2C Jewels",
"teamId": 4289
},
"reviewDisposition": null,
"uuid": "301f2cfc-3b67-4fc0-bf83-19099c2ea4bf"
},
]
You will have to create a class named as cases and then you need to map your json to the List then you can iterate through the list hope it will work for you .
List<cases> = new JavaScriptSerializer().Deserialize<List<cases>>(your json string);
You can install Json.Net package from Nuget and then add this line of code in you project
var myList = Newtonsoft.Json.JsonConvert.DeserializeObject("Your Json String..!!");
this should do it
I have a REST Service calling a WCF service. The method in WCf service returns data as expected. Here is the Json format of the c#object.
[
{
"$id": "1",
"children": [],
"id": 1,
"name": "1",
"owner": {
"userId": 1,
"username": "testuser",
"firstName": null,
"lastName": null
},
"parent": null,
"permissions": [],
"type": 0
}
]
When There is a complex object the WCf service is throwing an error "The underlying connection was closed: The connection was closed unexpectedly"
[
{
"$id": "1",
"Children": [
{
"$id": "2",
"Children": [],
"Id": 603268262,
"Name": "testfolder",
"Owner": {
"UserId": 555,
"Username": "testuser",
"FirstName": null,
"LastName": null
},
"Parent": {
"$ref": "1"
},
"Permissions": null,
"Type": 0
}
],
"Id": 1,
"Name": "555",
"Owner": {
"UserId": 555,
"Username": "testuser",
"FirstName": null,
"LastName": null
},
"Parent": null,
"Permissions": null,
"Type": 0
}
]
I have tried most answers on this SO question. Why do I get the error only when a complex object is returned?
you need to check data contracts ,take a look at this : http://msdn.microsoft.com/en-us/library/aa347850.aspx
Found the answer just after posting the question. I did notice that there is a object holding a reference to a object in the Json
"Parent": {
"$ref": "1"
}
This is preventing the object from serialized. I did a deep copy and that fixed the issue