Converting wikipedia api response using Json.net - c#

I'm querying data using wikipedia api and would like to convert the result into a string[].
The query "test"
en.wikipedia.org/w/api.php?action=opensearch&search=test&format=json&callback=spellcheck
returns this result here:
spellcheck(["test",["Test cricket","Test","Testicle","Testudines","Testosterone","Test pilot","Test (assessment)","Testimonial match","Testimony","Testament (band)"]])
Can I use Json.net to drop or ignore the tag "spellcheck"?
If I convert the response using this code, the application crashes:
Dictionary<string, string[]> dict = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(response);

Wikipedia's api (using JSON) assumes you're using JSONP. You could just drop the callback parameter completely from your query string:
en.wikipedia.org/w/api.php?action=opensearch&search=test&format=json
Additionally, the result you're getting probably cannot be converted into a Dictionary<string, string[]>. If you look closely, it's actually an array where the first object is a string (search term) and the second is a list of strings (results).
The following worked for me:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
#"http://en.wikipedia.org/w/api.php?action=opensearch&search=test&format=json");
string[] searchResults = null;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
JArray objects = JsonConvert.DeserializeObject<JArray>(reader.ReadToEnd());
searchResults = objects[1].Select(j => j.Value<string>()).ToArray();
}
}

Related

List<JToken> returned as empty array in JSON

I am trying to read a json file and parse it using
jArray = JArray.Parse(json);
And filtering that array based on some conditions and returning same in ActionREsult OK
var categories = jArray.SelectTokens("[*]")
.Where(token => (string)token.SelectToken(jPath) == displayLevel);
return Ok(categories);
But on client side I am receiving it as json string with empty array like this
[[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]],[[[]],[[]],[[]],[[]],[[]]]]
All this was working before.

How to convert a string json to a dictionary in C#

I have a simple WinForm program that does a WebRequest to a server, the response is a string looking like:
{"a":"foo","b":"bar"}
How do convert this string to a dictionary? (Dictionary<string, string>). Is there a built-in function I can use?
Use a library like JSON.NET:
var dictionary = JsonConvert.DeserializeObject<IDictionary<string, string>>(json)
var sourve = #"{"a":"foo","b":"bar"}";
Dictionary<string, string> result = JsonConvert.DeserializeObject<Dictionary<string, string>>(source);
If you can add two assemblies:
System.Web
System.Web.Extensions
You can use this code:
string html = "{\"a\":\"foo\",\"b\":\"bar\"}";
JavaScriptSerializer jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, string>>(html);

loop on data returned after deserializing

I get data from instagram api. So i use below
var responseStream = webRequest.GetResponse().GetResponseStream();
Encoding encode = System.Text.Encoding.Default;
using (StreamReader reader = new StreamReader(responseStream, encode))
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(reader.ReadToEnd());
}
I dont know how to loop on this data. I tried
foreach (var item in jsonObject)
{
}
But it gives compile time error Type object is not enumerable
How do i loop?
Your variable jsonObject is an object which is not an enumerable.
You must specify an enumerable type when deserializing :
var jsonObject = serialize.Deserialize<enumerableType>(reader.ReadToEnd());

Inserting a Row in BigQuery with Nested Record using C# API

I'm trying to insert a row (with nested records) into BigQuery using the C# API. I'm able to insert a row (w/ nested records) using the JavaScript API. But using the C# API i'm getting error saying: "Repeated field must be imported as a JSON Array". He is a simple row that I was able to insert using the JavaScript API
var json = {'rows':[{'json':
{"inputs" : [{
"Age":"10"
}]}}]};
This works fine in JS, but I'm unclear how to do this in C#.
Here is my attempt:
var r = new TableDataInsertAllRequest.RowsData();
r.Json = new Dictionary<string, object>();
var dict = new Dictionary<string, object>();
dict.Add("Age", "10");
r.Json.Add("inputs", dict);
Also I tried using JSON API
string json = JsonConvert.SerializeObject(input, jsonSettings);
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, jsonSettings);
r.Json.Add("jsonInputs", dict);
Here is the API Doc for RowsData https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/csharp/latest/classGoogle_1_1Apis_1_1Bigquery_1_1v2_1_1Data_1_1TableDataInsertAllRequest_1_1RowsData.html
Its somewhat vague or unclear how to do nested records. I tried just writing straight JSON but getting the same errors.
Any help would be much appreciated.
Thanks,
From the json example that works there are two arrays. I don't see any arrays in either of two failing examples you provide.
I suspect adding the arrays will fix your problem. Consider parsing the known-working json string into a json object and using that as a quick test.
The following code snippet successfully works for bigquery:
JArray inputs = new JArray();
JObject inputOne = new JObject(new JProperty("Age", "12"));
inputOne.Add(new JProperty("BirthDate", "1234"));
r.Json.Add("inputs", inputs);

Convert dictionary object to string to output as json

I am using razor in webmatrix.
I have a dictionary object
var occupancyTotalDic = new Dictionary<double, int>();
Once I have filled the dictionary with data I wish to output as JSON as a response to populate a flot chart
Dictionary<String, String> input = new Dictionary<String, String>();
occupancyTotalDic = input.ToDictionary(item => item.Key, item => (String)item.Value);
Response.ContentType = "application/json";
Response.Write(Json.Encode(occupancyTotalDic));
How do I convert my dictionary to contain strings so that I can output as JSON?
Since Webmatrix can't compile MVC application I assume you are using ASP.NET webforms.
Tried this solution https://stackoverflow.com/a/5597628/713789
If you are using MVC then just use JsonResult test(){ return Json(myobj);}

Categories

Resources