I would like to add two custom headers for a DELETE request to a string.
I have the following code
Dictionary<string, string> customHeaders = new Dictionary<string, string>();
customHeaders.Add("If-Match", passedEtag);
customHeaders.Add("context_study_site", "edc42643-27b5-428e-b8ae-2fa19bfb457a");
I have tried the following
StringBuilder sb = new StringBuilder();
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine + "Context headers passed in the request" + Environment.NewLine);
Dictionary<string, string> customHeaders = new Dictionary<string, string>();
customHeaders.Add("If-Match", passedEtag);
customHeaders.Add("context_study_site", "edc42643-27b5-428e-b8ae-2fa19bfb457a");
string test = customHeaders.ToString();
File.WriteAllText("C:\\Testing", "headersoutput.txt");
But I get the following
System.Collections.Generic.Dictionary`2[System.String,System.String]
System.Collections.Generic.Dictionary`2[System.String,System.String]
Rather than the two header key value pairs.
Any ideas much appreciated.
Thanks in advance.
Instead of .ToString() you need to Serialize your dictionary using JsonConvert.SerializeObjec()
var jsonDict = JsonConvert.SerializeObject( myDictionary );
Then write it to a file,
File.WriteAllText(#"C:\Testing\headersoutput.txt", jsonDict);
Why you are getting System.Collections.Generic.Dictionary2[System.String,System.String] in the your file?
You are trying to convert a Dictionary to string using
.ToString() method. You are not overriding its basic functionality,
so it calls the basic implementation of .ToString() method present
in Object class.
Returns a string that represents the current object.
MSDN: Basic implementation of Object.ToString()
How we solved it?
We used JsonConvert.SerializeObject() method from
Newtonsoft.Json library, which convert object(In your case
it is a dictionary), to a json string
Serializes the specified object to a JSON string.
Related
I'm relatively new to C# programming and have had my first encounter with objects. A method that I am using is returning an object and I am setting it to an object of my own as such,
object target = searchResponse.Result.Parameters.Values;
From here I'm attempting to extract the data from the object, but it seems to be a "complex" object (just came up with that terminology, it's probably wrong, but I don't know the correct term). According to the Visual Studio locals menu, the object's value is count = 2. But, 'inside' the object is the data that I want, as shown below:
How would I get to these pieces of data?
As #UnholySheep suggested use var wherever possible if you don't know the DataType beforehand.
But for instance as you have stored the data in target and as in the picture it's of type Dictionary, you can cast it
Dictionary<string, object> dict = target as Dictionary<string, object>;
Now you can access your data from dict
EDIT 1:
I assumed you may want to know how to access data from a Dictionary, so here is a short snippet:
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
//here _int_ will be the key, _string_ will be your data
myDictionary.Add(1, "abc"); //1 is key, abc is data
myDictionary.Add(2, "def");
myDictionary.Add(3, "ghk");
string myData = myDictionary[2]; //pass the value to be fetched
//myData = def
I need to parse lots of long json strings. Newtonsoft.Json is slow and I try to use fastjson.
I don't have the object class so I use the following code to get values when using Newtonsoft.Json:
JObject jo = (JObject)JsonConvert.DeserializeObject(addressBook);
string floor = jo["Street"]["building"]["floor"].ToString();
When I turn to use fastjson and use the JSON.Parse(string), I got an Dictionary<string, object>. And if I want to get the 'floor' value, I need to do the casting for each level like below:
var ob = (Dictionary<string, object>)JSON.Parse(addressBook);
var street = (Dictionary<string, object>)ob["Street"];
var building = (Dictionary<string, object>)street["building"];
var floor= (Dictionary<string, object>)building["floor"];
Does anyone know fastjson support it or not? And can it still be fast?
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);
I got this piece of code from somewhere in stackoverflow. I am unable to understand it. It is used to login to youtube. Iam new to C# and OOPS. So can anyone explain me few thigs:
1) In the 3rd line
HttpWebRequest request = GetNewRequest("https://accounts.google.com/ServiceLoginAuth", cookies);
HttpWebRequest is a class and request is a object. But why New keyword is not used after that? and What is this "GetNewRequest" ? Is it a method? most of the time we use constructor of the class there with New keyword. So can I conclude that I can use any method of the class there? There is no need to use the new keyword and the constructor?
2) In the 6th line
Dictionary<string, string> parameters = new Dictionary<string, string>
Dictionary is class and parameters is the object. But what is this <string, string> there? I never seen parameters can be passed to a class.
3) In the 7th line
{
{"continue","https%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26feature%3Dsign_in_button%26nomobiletemp%3D1%26hl%3Den_US%26next%3D%252F"},
{"service","youtube"},{"uilel","3"},{"dsh","157212168103955870"},{"hl","en_US"},
{"GALX","PTqcwpZb2aE"},{"pstMsg","1"},{"dnConn",""}, {"checkConnection","youtube%3A248%3A1"},
{"checkedDomains","youtube"}, {"timeStmp",""}, {"secTok",""}, {"Email","username"}, {"Passwd","password"},
{"signIn","Sign+in"}, {"PersistentCookie","yes"}, {"rmShown","1"}};
I can't understand what is this? It cant fit to any syntax I read in C#. It is something I have never seen before.
COMPLETE CODE
public void Login()
{
HttpWebRequest request = GetNewRequest("https://accounts.google.com/ServiceLoginAuth", cookies);
request.Referer = "https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26feature%3Dsign_in_button%26nomobiletemp%3D1%26hl%3Den_US%26next%3D%252F&uilel=3&hl=en_US&service=youtube";
request.Host = "accounts.google.com";
Dictionary<string, string> parameters = new Dictionary<string, string>{
{"continue","https%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26feature%3Dsign_in_button%26nomobiletemp%3D1%26hl%3Den_US%26next%3D%252F"},
{"service","youtube"},{"uilel","3"},{"dsh","157212168103955870"},{"hl","en_US"},
{"GALX","PTqcwpZb2aE"},{"pstMsg","1"},{"dnConn",""}, {"checkConnection","youtube%3A248%3A1"},
{"checkedDomains","youtube"}, {"timeStmp",""}, {"secTok",""}, {"Email","username"}, {"Passwd","password"},
{"signIn","Sign+in"}, {"PersistentCookie","yes"}, {"rmShown","1"}};
HttpWebResponse response = MakeRequest(request, cookies, parameters);
response.Close();
}
GetNewRequest would be a method that actually creates and returns the instance of HttpWebRequest. So, new is not needed before the call to GetNewRequest. new is only needed when you are calling the constructor of the type in that same line as the declaration.
The <string, string> declaration after Dictionary specifies the key and value types, since Dictionary<TKey, TValue> is a generic type.
That is a way of initializing a dictionary with a list of key/value pairs. It's just syntactic sugar. See Object Initialization. It's just there to make your life easier/code more concise. That code is equivalent to the more verbose:
_
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("continue","https%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26feature%3Dsign_in_button%26nomobiletemp%3D1%26hl%3Den_US%26next%3D%252F");
parameters.Add("service","youtube");
// etc.
GetNewRequest is a method which is not defined in the code you posted.
Dictionary<string, string> the < and > signs are used for generics, see
http://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx for an introduction.
Is the syntax for initializing the values of the dictionary, see http://msdn.microsoft.com/en-us/library/bb384062.aspx
I'm using an API from OpenCalais that gives me a json string that contains a bunch of JSON objects. The problem is that depending on what I pass into the API the structure of the JSON string changes, which means that I can't cast the deseralization against a custom class I could make. Another problem is that the output isn't in key value form, but rather a complicated object structure. Here is an example of the output-
{"doc":
{"info":
{"allowDistribution":"true",
"allowSearch":"true",
"calaisRequestID":"c1cdd79a-ed89-8431-138c-50e8a37100f9",
"externalID":"17cabs901",
"id":"http://id.opencalais.com/0RCcU306*HTR05*7HlUb5A",
"docId":"http://d.opencalais.com/dochash-1/6188237f-a2a5-3263-95b7-ea894ba98298",
"document":"Bill Gates worked at Microsoft from 2008 to 2011. He is also married to Melinda Gates.",
"docTitle":"",
"docDate":"2012-07-26 15:51:00.885",
"externalMetadata":"",
"submitter":"ABC"}
So you can see there are multiples levels of objects here and there is no key value structure. What I need from this code is essentially all of the name/value info in a dictionary. Then I can sort through based on the keys to the relevant info. It would also be cool if I could somehow also grab the parent of the object value. So for example the output I want is key: allowSearch, value: true, parent: info. I have been trying to mess around with different method of deserialization, dynamic objects, and just plain parsing using functions like .Ancestor and I haven't found anything useful. Any help would be greatly appreciated.
Have you looked at JSON.NET? It can dynamically parse JSON which you can then iterate through:
using Newtonsoft.Json.Linq;
JObject rootObject = JObject.Parse(jsonString);
You can iterate through the children, or search for other nodes like this:
JToken info = rootObject.SelectToken("info");
Json.NET support LINQ to JSON under the Newtonsoft.Json.Linq namespace.
The example to use JObject
JObject o = JObject.Parse(#"{'CPU': 'Intel','Drives': ['DVD read/writer','500 gigabyte hard drive']}");
string cpu = (string)o["CPU"];
// Intel
string firstDrive = (string)o["Drives"][0];
// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive
You can use DeserializeObject which essentially returns a Dictionary<string, object>.
For example:
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> myGraph = (Dictionary<string, object>)serializer.DeserializeObject(myJson);
To read stuff from the myGraph dictionary, you will have to cast each step of the way.
For example:
Dictionary<string, object> doc = (Dictionary<string, object>)myGraph["doc"];
Dictionary<string, object> info = (Dictionary<string, object>)doc["info"];
string externalID = (string)info["externalID"];
I'm sure you could genericize it a bit, but I think that should work with the json you posted.