Deserialize GET response - c#

How do I deserialize this text. I tried with JSON but I get "Invalid JSON primitive" error.
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 1
},
"objects": [
{
"blocked": false,
"groups": [],
"id": "1111",
"name": "John Doe",
"number": "+15555555555",
"resource_uri": "/api/v1/contacts/1111/"
}
]
}
This is the code I used:
var jss = new JavaScriptSerializer();
var dictionary = jss.Deserialize<Dictionary<string, string>>(buffer.ToString());

Easy to Fix. Deserialize to <Dictionary<string, object> instead of <Dictionary<string, string>
var dictionary = jss.Deserialize<Dictionary<string, object>>(buffer.ToString());
Full test code
string json = #"{
""meta"": {
""limit"": 20,
""next"": null,
""offset"": 0,
""previous"": null,
""total_count"": 1
},
""objects"": [
{
""blocked"": false,
""groups"": [],
""id"": ""1111"",
""name"": ""John Doe"",
""number"": ""+15555555555"",
""resource_uri"": ""/api/v1/contacts/1111/""
}
]
}";
var jss = new JavaScriptSerializer();
var dictionary = jss.Deserialize<Dictionary<string, object>>(json);

Related

How to serialize a dictionary to an array of json objects

I have a dictionary as shown below:
var tableData = new Dictionary<string, string>();
tableData["name"] = "Sam";
tableData["city"] = "Wellington";
tableData["country"] = "New Zealand";
How can I convert the above dictionary to a serialized json data as below:
[
{ "key": "name", "val": "Sam" },
{ "key": "city", "val": "Wellington" },
{ "key": "country", "val": "New Zealand" }
]

How to get all value of particular key in JSON?

I have a JSON structure that contains different levels. How to iterate the JSON and get all values of a particular key in JSON in C#
Below is my JSON file
{
"name": "EPM Company",
"id": "kpfwzgmhpm",
"type": "root",
"childern": [
{
"cid": "67",
"cname": "cname1",
"childern": [
{
"reading": [
{
"id": 121,
"name": "test1"
},
{
"id": 1121,
"name": "test11"
}
]
}
]
},
{
"cid": "454",
"cname": "cname14",
"childern": [
{
"reading": [
{
"id": 454,
"name": "test14"
},
{
"id": 21,
"name": "test141"
}
]
}
]
}
]
}
This is the JSON format. I am trying to get the value in the below format.
{
"name": "EPM Company",
"id": "kpfwzgmhpm",
"value": [
{
"id": 121,
"name": "test1",
"cid": "67",
"cname": "cname1"
},
{
"id": 1121,
"name": "test11",
"cid": "67",
"cname": "cname1"
},
{
"id": 124234,
"cname": "test12342",
"cid": "67",
"name": "cname1"
},
{
"id": 454,
"name": "test14",
"cid": "454",
"cname": "cname14"
},
{
"id": 21,
"name": "test141",
"cid": "454",
"cname": "cname14"
},
{
"id": 121,
"name": "test123122",
"cid": "454",
"cname": "cname14"
}
]
}
fetching all the reading key and its value-added to array with its cid and came. is it possible?
advanced thanks for the help
my code in c# is
public string SensorList(string entireData)
{
if (string.IsNullOrEmpty(entireData))
{
return string.Empty;
}
var returnObj = new Jobject ();
JObject o = JObject.Parse(entireData);
var childern = o["children"];
returnObj.Add("name" = o ["name"];
returnObj.Add("id" = o ["id"];
returnObj.Add("value" = o ["value"];
var valuearry = new JArray();
foreach(var data in childern)
{
foreach(var reading in data["reading"])
{
var valobj = new Jobject ();
valobj.Add( "cid",data["id"])
valobj.Add( "cname",data["name"])
valobj.Add( "name",reading["id"])
valobj.Add( "id",reading["name"])
valuearry.add()
if(data.containsKey("children"))
{
var sensorInfo = SensorList(data["children"]);
}
}
returnObj.Add("value",valuearry);
// var output = sensorInfo.SelectMany(x => ((JObject)x).Properties().Select(y => new JObject {
// new JProperty("id",y.Name),
// new JProperty("name",y.Value["name"])
// })).ToList();
// var returnArray = new JArray(output);
return returnObj.ToString();
}
}
recurring part is not working and take too much time for other long JSON file

Get certain value from JSON string

I have the following code which gets me the entire JSON string; however, I want to get just the cashprice for this.
string url = "http://ondemand.websol.barchart.com/getGrainBids.json?apikey=12345&location=54943&commodityName=Corn%20(%232%20Yellow)&bidsPerCom=2";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
string json = responseReader.ReadToEnd();
string data = JObject.Parse(json)["bids/price"].ToString();
Label1.Text = data;
}
}
The part I have commented out is what I want to work but each time I try that it returns just a null value. This is the JSON string that shows when the reader runs:
{
"status": {
"code": 200,
"message": "Success."
},
"results": [
{
"bids": [
{
"id": "19699878",
"commodity": "CORN",
"symbol": "ZCH19",
"delivery_start": "2019-03-01 00:00:00",
"delivery_end": "2019-03-31 23:59:59",
"basis": "-35.00",
"notes": null,
"active": true,
"sym_root": "ZC",
"commodity_id": "119555",
"customer_commodity_id": "5813",
"commodity_display_name": "Corn (#2 Yellow)",
"unitvalue": 1,
"unitweight": 56,
"deliveryMonth": "Mar19",
"deliveryYear": "2019",
"basismonth": "Mar 2019",
"timestamp": 1544543949,
"as_of": "09:59",
"price": "3.48",
"pricecwt": "6.205357",
"basiscwt": -62.5,
"pricetonne": "136.804545",
"basistonne": -1377.8875,
"change": "-0.015",
"rawchange": -0.015,
"pctchange": "-0.43",
"cashprice": "3.48",
"cashpricetonne": "136.804545",
"delivery_sort": "2019-03-01 00:00:00",
"delivery_start_raw": "2019-03-01 00:00:00",
"delivery_end_raw": "2019-03-31 23:59:59",
"basisSymbol": "ZCBH19-54943-5813.CM",
"cashPriceSymbol": "ZCPH19-54943-5813.CM"
},
{
"id": "14938531",
"commodity": "CORN",
"symbol": "ZCZ19",
"delivery_start": "2019-12-01 00:00:00",
"delivery_end": "2019-12-31 23:59:59",
"basis": "-45.00",
"notes": null,
"active": true,
"sym_root": "ZC",
"commodity_id": "119555",
"customer_commodity_id": "5813",
"commodity_display_name": "Corn (#2 Yellow)",
"unitvalue": 1,
"unitweight": 56,
"deliveryMonth": "Dec19",
"deliveryYear": "2019",
"basismonth": "Dec 2019",
"timestamp": 1544543947,
"as_of": "09:59",
"price": "3.56",
"pricecwt": "6.361607",
"basiscwt": -80.3571428571,
"pricetonne": "140.249263",
"basistonne": -1771.56964286,
"change": "-0.01",
"rawchange": -0.01,
"pctchange": "-0.28",
"cashprice": "3.56",
"cashpricetonne": "140.249263",
"delivery_sort": "2019-12-01 00:00:00",
"delivery_start_raw": "2019-12-01 00:00:00",
"delivery_end_raw": "2019-12-31 23:59:59",
"basisSymbol": "ZCBZ19-54943-5813.CM",
"cashPriceSymbol": "ZCPZ19-54943-5813.CM"
}
],
"distance": null,
"company": "Ag Partners",
"locationId": 54943,
"location": "Brown/Sab/Rulo/WC",
"facility_type": "Country Elevator",
"address": "2750 Acorn Rd",
"city": "Sabetha",
"state": "KS",
"lng": -95.786193,
"lat": 39.9061537,
"phone": "785-284-2185",
"url": "www.agpartnerscoop.com",
"zip": "66534",
"county": "Nemaha County",
"basisTimestamp": "2018-12-11T09:02:48-06:00"
}
]
}
Any suggestions how to get the 3.48 show correctly? I'm sure it's something small I'm missing.
There are multiple bids in the JSON. If you just want to get the first one, you can use SelectToken and supply a path like this:
JObject jo = JObject.Parse(json);
string cashPrice = (string)jo.SelectToken("results[0].bids[0].cashprice");
Label1.Text = cashPrice;
Fiddle: https://dotnetfiddle.net/rUklUq
If you want to get prices for all bids, you can use SelectTokens and use a wildcard like this:
JObject jo = JObject.Parse(json);
List<string> allPrices = jo.SelectTokens("results[0].bids[*].cashprice")
.Values<string>()
.ToList();
Fiddle: https://dotnetfiddle.net/lGbJEe
For things like this we like to use JsonPaths. Here is our go to references if you want to try that way. http://jsonpath.com/ and https://goessner.net/articles/JsonPath/index.html#e2
var data = JObject.Parse(json).SelectTokens("$.results[*].bids[*].price");
var result = data;
You need to convert the Json string into a Json Object and get the results array.
JSONObject jsonObject = new JSONObject(jsonString);
Once you have the Json Object you need to get the results[] and loop through it to get the Bids[] and in there you can get cashprice.
Brian had the perfect answer:
JObject jo = JObject.Parse(json);
string cashPrice = (string)jo.SelectToken("results[0].bids[0].cashprice");
Label1.Text = cashPrice;

How to safely deserialize keys/data format JSON response

I am getting this 'optimized' JSON response from a third party web service presented as follows, I built the type as per the information presented in the keys but the difficulty I am facing is that data is not represented in objects but in arrays, is there a way to automate the building and value mapping of my objects list?
{
"reports": {
"query": {
"keys": [{
"name": "Date",
"type": "date"
}, {
"name": "NetSales",
"type": "price"
}, {
"name": "GrossCash",
"type": "price"
}, {
"name": "GrossCard",
"type": "price"
}, {
"name": "GrossDelivery",
"type": "price"
}, {
"name": "NetFood",
"type": "price"
}, {
"name": "NetDrink",
"type": "price"
}, {
"name": "NetRetail",
"type": "price"
}, {
"name": "Baskets",
"type": "int"
}],
"data": [
[1523577600000, 51924, 11300, 27200, 9900, null, null, null, 8],
[1523404800000, 7434, 2600, 3900, null, null, null, null, 6],
[1523491200000, 18101, 4000, 10100, null, null, null, null, 5],
[1523664000000, 13243, 7400, 6500, null, null, null, null, 3],
[1523750400000, 11718, 7300, null, 5000, null, null, null, 2],
[1523836800000, 16576, 7700, 4800, 4900, null, null, null, 4],
[1524096000000, 20293, 9100, 6000, null, null, null, null, 4]
]
}
},
"api": {
"message": {
"success": {
"202": {
"id": 202,
"title": "Token is valid",
"details": "Token is validated and found valid."
}
}
},
"codeBaseVersion": 1,
"executionTime_milliSeconds": 43
}
}
I ended up with this code but not satisfied with it:
JObject myOpject = JObject.Parse(responseString);
List<JToken> setOfObjects = myOpject["reports"]["query"]["data"].Children().ToList();
var listOfData = new List<Data2>();
foreach (var token in setOfObjects)
{
var myObject = new Data2
{
NetSales = decimal.Parse(token[1].ToString()),
//etc.
};
listOfData.Add(myObject);
}
using the same JToken idea transform the data using the keys to create a new object model and then deserialize that to the strong type desired.
For example, taking a few records you can transform the keys and data to
[
{
"Date": 1523577600000,
"NetSales": 51924,
...
},
{
"Date": 1523404800000,
"NetSales": 7434,
...
},
...
]
The following code attempts to build that using the key index matched to the index of item in data array
JObject myOpject = JObject.Parse(responseString);
List<JToken> keys = myOpject["reports"]["query"]["keys"].Children().ToList();
List<JToken> data = myOpject["reports"]["query"]["data"].Children().ToList();
var array = new JArray();
foreach (var token in data) {
var record = new JObject();
for (var i = 0; i < keys.Count; i++) {
var propertyName = keys[i]["name"].Value<string>();
var propertyValue = token[i];
record[propertyName] = propertyValue;
}
array.Add(record);
}
var listOfData = array.ToObject<List<Data2>>(); // or Data2[], etc
assuming Data2 is your strongly typed model with matching properties.

How to access elements of a JArray (or iterate over them)

I have the following Json gotten from Twitter
+ token {[
{
"trends": [
{
"name": "Croke Park II",
"url": "http://twitter.com/search?q=%22Croke+Park+II%22",
"promoted_content": null,
"query": "%22Croke+Park+II%22",
"events": null
},
{
"name": "#twiznight",
"url": "http://twitter.com/search?q=%23twiznight",
"promoted_content": null,
"query": "%23twiznight",
"events": null
},
{
"name": "#Phanhattan",
"url": "http://twitter.com/search?q=%23Phanhattan",
"promoted_content": null,
"query": "%23Phanhattan",
"events": null
},
{
"name": "#VinB",
"url": "http://twitter.com/search?q=%23VinB",
"promoted_content": null,
"query": "%23VinB",
"events": null
},
{
"name": "#Boston",
"url": "http://twitter.com/search?q=%23Boston",
"promoted_content": null,
"query": "%23Boston",
"events": null
},
{
"name": "#rtept",
"url": "http://twitter.com/search?q=%23rtept",
"promoted_content": null,
"query": "%23rtept",
"events": null
},
{
"name": "Facebook",
"url": "http://twitter.com/search?q=Facebook",
"promoted_content": null,
"query": "Facebook",
"events": null
},
{
"name": "Ireland",
"url": "http://twitter.com/search?q=Ireland",
"promoted_content": null,
"query": "Ireland",
"events": null
},
{
"name": "Everton",
"url": "http://twitter.com/search?q=Everton",
"promoted_content": null,
"query": "Everton",
"events": null
},
{
"name": "Twitter",
"url": "http://twitter.com/search?q=Twitter",
"promoted_content": null,
"query": "Twitter",
"events": null
}
],
"as_of": "2013-04-17T13:05:30Z",
"created_at": "2013-04-17T12:51:41Z",
"locations": [
{
"name": "Dublin",
"woeid": 560743
}
]
}
]} Newtonsoft.Json.Linq.JToken {Newtonsoft.Json.Linq.JArray}
Problem is I can't seem to access any of the elements. I have tried foreach loops and normal for loops and can never seem to access individual elemets it always ends up accessing the whole area.
Any idea how I access the individual elements in this Json JArray?
There is a much simpler solution for that.
Just treat the items of the JArray as JObject.
Let's say we have such array of JSON objects:
JArray jArray = JArray.Parse(#"[
{
""name"": ""Croke Park II"",
""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
""promoted_content"": null,
""query"": ""%22Croke+Park+II%22"",
""events"": null
},
{
""name"": ""Siptu"",
""url"": ""http://twitter.com/search?q=Siptu"",
""promoted_content"": null,
""query"": ""Siptu"",
""events"": null
}]");
To get access each item just do the following:
foreach (JObject item in jArray) // <-- Note that here we used JObject instead of usual JProperty
{
string name = item.GetValue("name").ToString();
string url = item.GetValue("url").ToString();
// ...
}
Update - I verified the below works. Maybe the creation of your JArray isn't quite right.
[TestMethod]
public void TestJson()
{
var jsonString = #"{""trends"": [
{
""name"": ""Croke Park II"",
""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
""promoted_content"": null,
""query"": ""%22Croke+Park+II%22"",
""events"": null
},
{
""name"": ""Siptu"",
""url"": ""http://twitter.com/search?q=Siptu"",
""promoted_content"": null,
""query"": ""Siptu"",
""events"": null
},
{
""name"": ""#HNCJ"",
""url"": ""http://twitter.com/search?q=%23HNCJ"",
""promoted_content"": null,
""query"": ""%23HNCJ"",
""events"": null
},
{
""name"": ""Boston"",
""url"": ""http://twitter.com/search?q=Boston"",
""promoted_content"": null,
""query"": ""Boston"",
""events"": null
},
{
""name"": ""#prayforboston"",
""url"": ""http://twitter.com/search?q=%23prayforboston"",
""promoted_content"": null,
""query"": ""%23prayforboston"",
""events"": null
},
{
""name"": ""#TheMrsCarterShow"",
""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
""promoted_content"": null,
""query"": ""%23TheMrsCarterShow"",
""events"": null
},
{
""name"": ""#Raw"",
""url"": ""http://twitter.com/search?q=%23Raw"",
""promoted_content"": null,
""query"": ""%23Raw"",
""events"": null
},
{
""name"": ""Iran"",
""url"": ""http://twitter.com/search?q=Iran"",
""promoted_content"": null,
""query"": ""Iran"",
""events"": null
},
{
""name"": ""#gaa"",
""url"": ""http://twitter.com/search?q=%23gaa"",
""promoted_content"": null,
""query"": ""gaa"",
""events"": null
},
{
""name"": ""Facebook"",
""url"": ""http://twitter.com/search?q=Facebook"",
""promoted_content"": null,
""query"": ""Facebook"",
""events"": null
}]}";
var twitterObject = JToken.Parse(jsonString);
var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;
foreach (var item in trendsArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
}
So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.
foreach(var item in yourJArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
Once you have a JArray you can treat it just like any other Enumerable object,
and using linq you can access them, check them, verify them, and select them.
var str = #"[1, 2, 3]";
var jArray = JArray.Parse(str);
Console.WriteLine(String.Join("-", jArray.Where(i => (int)i > 1).Select(i => i.ToString())));
void ConvertToJArray(object headers)
{
//where headers is your Twitter response
JObject JObj = (JObject)headers;//Parse to JObject
JArray JArr = (JArray)JObj["trends"];//Get the trends array as JArray
for (int i = 0; i < JArr.Count; i++)
{
var Name = JArr[i]["name"].ToString();
var URL = JArr[i]["url"].ToString();
}
}

Categories