How do I convert a querystring to a json string? - c#

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.

Related

Flat dictionary to JSON string?

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)));

Can lambda expressions be used on dynamic list to get results

I have following code:
dynamic jsonData = JObject.Parse(data);
var names= new List<dynamic>();
names= jsonData.Properties().Select(p => p.first_name).ToList();
I am unable to make this work as keep on getting error cannot use lambda. Is there a way to get this result? Or should I not use dynamic here?
Json string:
{"items":[{"id":404,"name":"Ken":{"id":215,"neighbourhood":"Mississauga"}]
,{"id":407,"name":"John":{"id":215,"neighbourhood":"Toronto"}]
,...
You don't need dynamic, I'd advise you not to use it, there's no point.
It appears you have an object with an items property which is an array of objects, and you're trying to grab the name of those objects. Just do this:
var obj = JObject.Parse(data);
var names = obj["items"]
.Select(item => (string)item["name"])
.ToList();
Try it like so
... ((IEnumerable<dynamic>)jsonData.Properties()).Select( ...

How to easily remove part of string from string array in c#

I am using following code:
var names = ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name"));
and i get keys like: name1, name2, name16, name18.
Now i want to create another array which will remove name and just keep 1,2,16,18. Is there any easy way to do this in above code itself? Or do it seperatly?
You can directly
ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name")).Select(a => a.Replace("name",""));
I think your code is good enough. Just a little bit of performance improve by using substring as it's straightforward operation to remove prefix:
var prefix = "name"; // could be a parameter or used as const; just for example
var nums = ConfigurationManager.AppSettings.AllKeys.Where(s => s.StartsWith(prefix)).Select(s => s.Substring(prefix.Length)).ToArray();
Try this:
var names = ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("name")).Select(p => p.Replace("name", ""));
Use:
var namesWithoutPrefix = names.Select(n => n.Substring(4));
Doing Replace instead of Substring might replace several substrings in one name (and is slower even if it doesn't do so).
I would not recommend relying on the position of the numeric value or the length of the string or the fact that the text reads 'name' at all. Instead you can use a simple regular expression to extract it consistently:
Regex regex = new Regex(#"[0-9]+");
var numbers = ConfigurationManager.AppSettings
.AllKeys.Select(p => regex.Match(p).Value).ToArray();

Convert a generic array to a specific type

I'm using Interop to work with Excel in C#. I need two cells. This is how I get them:
cells = (Excel.Range)sheet.get_Range("V" + i, "W" + i);
System.Array values = (System.Array)cells.Cells.Value;
This returns the values I want, as tested with a foreach loop. But how do I get the elements into string variables? I tried this:
var stringValues = values.Cast<string>();
but I can't access it in any way without raising an error.
A simple ConvertAll should suffice:
var stringValues = Array.ConvertAll(values, item => (string)item);
the code var stringValues = values.Cast<string>(); is attempting to cast the array as a string. so, if you are trying to end up with an array of strings you can try:
var stringValues = new List<string>();
values.ToList().ForEach(cellValue=>stringValues.Add(cellValue.ToString());
this is off the top of my head, there is probably a terser way of expressing this
You can try:
values.Select(o => o.ToString());

Using LINQ to parse XML into Dictionary

I have a configuration file such as:
<ConfigurationFile>
<Config name="some.configuration.setting" value="some.configuration.value"/>
<Config name="some.configuration.setting2" value="some.configuration.value2"/>
...
</ConfigurationFile>
I am trying to read this to XML and convert it to a Dictionary. I tried coding something liek this but it is obviously wrong as it does not compile.
Dictionary<string, string> configDictionary = (from configDatum in xmlDocument.Descendants("Config")
select new
{
Name = configDatum.Attribute("name").Value,
Value = configDatum.Attribute("value").Value,
}).ToDictionary<string, string>(Something shoudl go here...?);
If someone could tell me how to get this working it would be really helpful. I could always, of course, read it
To give a more detailed answer - you can use ToDictionary exactly as you wrote in your question. In the missing part, you need to specify "key selector" and "value selector" these are two functions that tell the ToDictionary method which part of the object that you're converting is a key and which is a value. You already extracted these two into an anonymous type, so you can write:
var configDictionary =
(from configDatum in xmlDocument.Descendants("Config")
select new {
Name = configDatum.Attribute("name").Value,
Value = configDatum.Attribute("value").Value,
}).ToDictionary(o => o.Name, o => o.Value);
Note that I removed the generic type parameter specification. The C# compiler figures that automatically (and we're using an overload with three generic arguments). However, you can avoid using anonymous type - in the version above, you just create it to temporary store the value. The simplest version would be just:
var configDictionary =
xmlDocument.Descendants("Config").ToDictionary(
datum => datum.Attribute("name").Value,
datum => datum.Attribute("value").Value );
Your call to ToDictionary needs a key and value selector. Starting with that you have, it can be
var dictionary = yourQuery.ToDictionary(item => item.Name, item => item.Value);
It isn't necessary to have the query as you're just doing a projection. Move the projection into the call to ToDictionary():
var configDictionary = xmlDocument.Descendants("Config")
.ToDictionary(e => e.Attribute("name").Value,
e => e.Attribute("value").Value);

Categories