Get a value from string array by search id - c#

I have a list of values in an array Cmnts like
"6_12_g2_text":"22","6_12_g3_text":"33","6_12_g4_text":"44"
var CmntsValue = forms["textvalue"];
string[] Cmnts = CmntsValue.Split('{','}');
No I want to search for 6_12_g2_text and return 22 (for 6_12_g3_text and return 33). How can i achieve this?
I got the value as shown in following image!
I insert my updated code here [in second image]. Kindly check with that

The value you have is actually a JSON string. Using Json.NET you can easily parse the string into a Dictionary<string, int>, like so:
var json = "{\"6_12_g2_text\":\"22\",\"6_12_g3_text\":\"33\",\"6_12_g4_text\":\"44\"}";
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, int>>(json);
And then extract any value by key:
int value;
if (dictionary.TryGetValue("6_12_g2_text", out value))
{
Console.WriteLine(value);
}
Edit:
After seeing your actual JSON string, you're going to have to do some additional work:
var json = "{\"1_3_g1_text\":\"11\"}
{\"1_3_g2_text\":\"\"}
{\"6_12_g2_text\":\"test\"}
{\"6_12_g3_text\":\"\"}
{\"1_17_g1_text\":\"works\"}
{\"5_19_g2_text\":\"submitted\"}
{\"5_19_g3_text\":\"2\"}";
var jsons = json.Split('{', '}').Where(x => !string.IsNullOrWhiteSpace(x));
var concatenatedJson = string.Format("{{{0}}}", string.Join(",", jsons));
var intermidiateDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(
concatenatedJson);

Related

How to Deserialize the dictionary and fetch the value of a particular key

How should I get the value of status key ?
string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\""
tried with JObject.Parse and JArray.Parse to deserialize it and fetch the value.
getting error all the time, even if the key is present.
PS: this value is coming directly from the DB, where it is stored as a string.
using System.Text.Json;
string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\"";
var json = JsonDocument.Parse(a).RootElement.GetString();
var jDoc = JsonDocument.Parse(json);
var dic = jDoc.RootElement[0].Deserialize<Dictionary<string, string>>();
var status = dic["Status"];
Maybe there is a better solution. But you can remove the / character and split by "
string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\"";
var val=a.Replace("\\", "").Split(new string[] { "\"" },
StringSplitOptions.None)[4];
Here is a method can get the value, hope it can give you some help.
using Newtonsoft.Json;
string a = "\"[{\\\"Status\\\":\\\"Passed\\\"}]\"";
var b = JsonConvert.DeserializeObject(a);
var c = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(b.ToString());

Parse string to different variables c#

I've got a string fdf=232232&lid=19974832&number=1&aa_result1_1=someId1&aa_resuuuuuult2_2=someId2&aa_resuuuult3_3=someId3
and if aa exists I need to take values and add them to dictionary like:
var dict = extendedIds.Add("result1", new Dictionary<string, int[]>()
{
{
"someId1",
new int[]{ 1 }
}, ...
});
however I am having a difficult time deciding how to parse it properly? I need to accept multiple aa values (the ones that come as resultN, someIdN and a number (which is the number after resultN_NUMBER).
I tried to use substring but that doesn't work as I dont't now the length of word result
Basically it is
var parameters = $"pam=805700&laaid=19974832&kpm=1&{HttpUtility.UrlEncode("aa_{result}_{number}={id}&aa_{result}_{number}={id}&aa_{result}_{number}={id}", Encoding.UTF8)}";
So I decode it and get string:
var decoded = input.ToString().UrlDecode();
I need to accept multiple aa values, so in this example there would be three values, two of them comes from in bertween _ one after = but I wonder how to take these values then there could be something else also split by _...
also I could var parsed = HttpUtility.ParseQueryString(decoded); parse to NameValueCollection. but I can't use parsed.GetValues("aa") because the key would be e.g. aa_result1_1 and I never know beforehand what it is
this is a query string, you can use HttpUtility.ParseQueryString to parse it
see
https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.parsequerystring?view=net-5.0
Would this set you on the right track?
var qs = "fdf=232232&lid=19974832&number=1&aa_result1_1=someId1&aa_resuuuuuult2_2=someId2&aa_resuuuult3_3=someId3";
var nvc = System.Web.HttpUtility.ParseQueryString(qs);
foreach (var key in nvc.AllKeys.Where(k => k.StartsWith("aa")))
{
var id = nvc[key];
var parts = key.Split('_');
var result = parts[1];
var number = parts[2];
Console.WriteLine($"result = '{result}', number = '{number}' => id = '{id}'");
}
Use ParseQueryString to convert your string into a NameValueCollection.
Then use each key that starts with "aa"
Get its value - this is your "id"
Split the key on the _
Ignore the first part (which would be "aa") and use the next two parts
Of course you would want to add some safety: I now assume that there always are 3 parts in that key. Plus you want to do something useful with the results.
The above code prints this
result = 'result1', number = '1' => id = 'someId1'
result = 'resuuuuuult2', number = '2' => id = 'someId2'
result = 'resuuuult3', number = '3' => id = 'someId3'

Deserialize Json into list using Json.net C#

I have a JSON data ( http://country.io/names.json ) like :
{"BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso", "BG": "Bulgaria", "BA": "Bosnia and Herzegovina", "BB": "Barbados" }
I want to list that json like CountryCode-CountryName (BD-Bangladesh) . How do I do that on windows form app. ?
You could deserialise the JSON into a Dictionary instead of a single object. This gives you access to all the codes and names, like so:
var json = #"{""BD"": ""Bangladesh"", ""BE"": ""Belgium"", ""BF"": ""Burkina Faso"", ""BG"": ""Bulgaria"", ""BA"": ""Bosnia and Herzegovina"", ""BB"": ""Barbados"" }";
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
foreach (var item in dict)
{
var countryCode = item.Key;
var countryName = item.Value;
// do whatever you want to do with those two values here
Console.WriteLine("CountryCode: {0} CountryName: {1}", countryCode, countryName);
}
In that code it simply writes it to the screen, but obviously once you have that loop in place you can do whatever you like with the country code and name.

extract variables and values from http post / string c#

I am trying to read in POST data to an ASPX (c#) page. I have got the post data now inside a string. I am now wondering if this is the best way to use it. Using the code here (http://stackoverflow.com/questions/10386534/using-request-getbufferlessinputstream-correctly-for-post-data-c-sharp) I have the following string
<callback variable1="foo1" variable2="foo2" variable3="foo3" />
As this is now in a string, I am splitting based on a space.
string[] pairs = theResponse.Split(' ');
Dictionary<string, string> results = new Dictionary<string, string>();
foreach (string pair in pairs)
{
string[] paramvalue = pair.Split('=');
results.Add(paramvalue[0], paramvalue[1]);
Debug.WriteLine(paramvalue[0].ToString());
}
The trouble comes when a value has a space in it. For example, variable3="foo 3" upsets the code.
Is there something better I should be doing to parse the incoming http post variables within the string??
You might want to treat it as XML directly:
// just use 'theResponse' here instead
var xml = "<callback variable1=\"foo1\" variable2=\"foo2\" variable3=\"foo3\" />";
// once inside an XElement you can get all the values
var ele = XElement.Parse(xml);
// an example of getting the attributes out
var values = ele.Attributes().Select(att => new { Name = att.Name, Value = att.Value });
// or print them
foreach (var attr in ele.Attributes())
{
Console.WriteLine("{0} - {1}", attr.Name, attr.Value);
}
Of course you can change that last line to whatever you want, the above is a rough example.

Simple way to read and write name value text file

I have some class with lots of fields;
public class CrowdedHouse
{
public int value1;
public float value2;
public Guid value3;
public string Value4;
// some more fields below
}
My classmust be (de)serialized into simple Windows text file in the following format
NAME1=VALUE1
NAME2=VALUE2
What is the most convinient way to do that in .NET? This is a text file and all the values must be fist converted to string. Let's assume I have already converted all data to strings.
UPDATE One option would be pinvoke WritePrivateProfileString/WritePrivateProfileString
but these are using the required "[Section]" field that I don't need to use.
EDIT: If you have already converted each data value to strings, simply use the method below to serialize it after making a Dictionary of these values:
var dict = new Dictionary<string, string>
{
{ "value1", "value1value" },
{ "value2", "value2value" },
// etc
}
or use dict.Add(string key, string value).
To read the data, simply split each line around the = and store the results as a Dictionary<string, string>:
string[] lines = File.ReadAllLines("file.ext");
var dict = lines.Select(l => l.Split('=')).ToDictionary(a => a[0], a => a[1]);
To convert a dictionary to the file, use:
string[] lines = dict.Select(kvp => kvp.Key + "=" + kvp.Value).ToArray();
File.WriteAllLines(lines);
Note that your NAMEs and VALUEs cannot contain =.
Writing is easy:
// untested
using (var file = System.IO.File.CreateText("data.txt"))
{
foreach(var item in data)
file.WriteLine("{0}={1}", item.Key, item.Value);
}
And for reading it back:
// untested
using (var file = System.IO.File.OpenText("data.txt"))
{
string line;
while ((file.ReadLine()) != null)
{
string[] parts = line.Split('=');
string key = parts[0];
string value = parts[1];
// use it
}
}
But probably the best answer is : Use XML.
Minor improvement of Captain Comic answer:
To enable = in values: (will split only once)
var dict = lines.Select(l => l.Split(new[]{'='},2)).ToDictionary(a => a[0], a => a[1]);

Categories

Resources