I have a dictionary like the below:
private readonly Dictionary<string, string> _packetData;
I try and convert a dictionary to json, I do json2dictionary also which just converts it to a flat dictionary, but this is in reverse, converting from dictionary2json.
public string GetJson()
{
var entries = _packetData.Select(d => string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
return "{" + string.Join(",", entries) + "}";
}
I've noticed that it doesn't wrap strings with double quotes each end, instead it does this.
{"test":test123}
What am I doing wrong?
There are no quotes in your output, because you haven't included quotes in your format string, just as you have with the key. I have removed your brackets ([ and ]), because they indicate an array value in JSON, and your dictionary has string values, so no need for string.Join().
var entries = _packetData.Select(d => string.Format("\"{0}\": \"{1}\"", d.Key, d.Value));
I would also recommend that you use the Newtonsoft's excellent Json.NET library, which you can find on nuget. Using a library instead of rolling your own implementation is more reliable and often more secure, and often means that you don't need to write as much code. In this case, it would be as simple as:
JsonConvert.SerializeObject(_packetData);
https://www.newtonsoft.com/json/help/html/SerializeDictionary.htm
var entries = _packetData.Select(d => string.Format("\"{0}\": [\"{1}\"]", d.Key, string.Join(",", d.Value)));
Related
Please consider the following inline code:
string.Join(",", context.Request.Headers.ToArray())
If the Headers structure above were a Dictionary(string, string), the code above would output the following:
[MyHeaderKey1, MyHeaderVal1],[MyHeaderKey2, MyHeaderVal2]
However, the Dictionary value is a string[] so the following gets output instead:
[MyHeaderKey1, System.String[]],[MyHeaderKey2, System.String[]]
I need to be able to generate output like the first code example but against the Dictionary with the string[] value. It's ok if I only take the first item of the Dictionary - string[] value. Can this be done with inline C#?
Yes. Use Linq Select.
string.Join(",", context.Request.Headers.Select(x => string.Format("[{0}, {1}]", x.Key, FormatThisArray(x.Value))))
EDIT: Since OP mentioned that the value is string[], the default x.Value as described above may not produced desired output. I'm not sure how OP would format the value of the dictionary item and assuming FormatThisArray is a function that formats the array.
You need to do something like this:
var result =
string.Join(",",
context.Request.Headers.Select(x =>
string.Format(
"[{0},{1}]",
x.Key,
"(" + string.Join(",", x.Value) + ")")));
This joins the individual items inside each string[] with a , and puts them between brackets.
Output would look like this:
[MyHeaderKey1,(v1,v2,v3)],[MyHeaderKey2,(v4,v5,v6)]
If you just need the fist value:
string.Join(",", context.Request.Headers.Select(d=>new {d.Key,Value=d.Value.FirstOrDefault()}));
I have a schema generated from BizTalk. it doesn't understand the dictionary collection so it simply converts that to array of key value pair of string and string. Now when i am redirecting the request in a service i get
Dictionary<string, string> valuePairs
When i looked in to the reference.cs file i can see like this:
public bool ProcessMessage(string code, string template, Service.Proxy.ArrayOfKeyValueOfstringstringKeyValueOfstringstring[] valuePairs)
How can i convert this dictionary to array of key value of string string using linq? I know it's easy to do this using linq but any help will really be appreciated.
I have so far tried this but doesn't work:
ArrayOfKeyValueOfstringstringKeyValueOfstringstring[] array =
valuePairs.Select(pair => string.Format("{0},{1}", pair.Key, pair.Value))
.ToArray(KeyValuePair<string,string>);
try below , you may need to change the set properties of new object accordingly
ArrayOfKeyValueOfstringstringKeyValueOfstringstring[] array =
valuePairs.Select(pair =>
new ArrayOfKeyValueOfstringstringKeyValueOfstringstring(){
Key= pair.Key, Value= pair.Value}).ToArray();
What you can do is this, which converts your dictionary to the desired array:
KeyValuePair<string, string>[] kvps = valuePairs.ToArray();
Using server-side C#, how can I convert a querystring to a JSON string of keys and values? For example, I want to convert
"ID=951357852456&FNAME=Jaime&LNAME=Lopez"
to
{ "ID":"951357852456" , "FNAME":"Jaime" , "LNAME":"Lopez" }
I know how to manually parse and format but, before starting down that road, I thought I'd ask since there might be a library that does it better. Thanks!
This gives the exactly same json you want
var dict = HttpUtility.ParseQueryString("ID=951357852456&FNAME=Jaime&LNAME=Lopez");
var json = new JavaScriptSerializer().Serialize(
dict.AllKeys.ToDictionary(k => k, k => dict[k])
);
It also possible to use
var collection = HttpUtility.ParseQueryString(query);
Newtonsoft.Json.JsonConvert.SerializeObject(collection.AllKeys.ToDictionary(y => y, y => collection[y]));
You can use jQuery to do this: jQuery.Param.
At the moment I'm using all sorts of if statements and substrings in order to manipulate the query string parameters and wanted to know if there was a more efficient way of doing it.
To be precise - I'm needing to add a query string parameter to the current url but if it already exists - I need to just amend it.
To clarify - I CAN achieve this using standard string manipulation methods, and I know how to retrieve the current url etc. I'm just wondering if these wheels are already in place and I'm re-inventing them.
HttpUtility.ParseQueryString(queryString);
For more: http://msdn.microsoft.com/en-us/library/system.web.httputility.parsequerystring.aspx
Probably you are looking for HttpUtility.ParseQueryString().
You could parse the query string as a Dictionary<string,string> and use this to manipulate and then simply format the key value pairs as appropriate when outputting as a query string once more:
public Dictionary<string, string> ToDictionary(string queryString)
{
return queryString.TrimStart('?').Split('&').Select(qp => qp.Split(',')).ToDictionary(a => a[0], a=> a[1]);
}
public Dictionary<string, string> ToString(Dictionary<string, string> queryString)
{
return '?' + string.Join('&', queryString.Select(kvp => kvp.Key + '=' + kvp.Value));
}
Is there a way to get all the querystring name/value pairs into a collection?
I'm looking for a built in way in .net, if not I can just split on the & and load a collection.
Yes, use the HttpRequest.QueryString collection:
Gets the collection of HTTP query string variables.
You can use it like this:
foreach (String key in Request.QueryString.AllKeys)
{
Response.Write("Key: " + key + " Value: " + Request.QueryString[key]);
}
Well, Request.QueryString already IS a collection. Specifically, it's a NameValueCollection. If your code is running in ASP.NET, that's all you need.
So to answer your question: Yes, there is.
You can use LINQ to create a List of anonymous objects that you can access within an array:
var qsArray = Request.QueryString.AllKeys
.Select(key => new { Name=key.ToString(), Value=Request.QueryString[key.ToString()]})
.ToArray();
If you have a querystring ONLY represented as a string, use HttpUtility.ParseQueryString to parse it into a NameValueCollection.
However, if this is part of a HttpRequest, then use the already parsed QueryString-property of your HttpRequest.
QueryString property in HttpRequest class is actually NameValueCollection class. All you need to do is
NameValueCollection col =
Request.QueryString;
Create dictionary of parameters
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters = Request.QueryString.Keys.Cast<string>().ToDictionary(k => k, v => Request.QueryString[v]);