Array of string into a string ready for JSON formatting - c#

I have an array of string values obtained from a method and I want to convert this array into a HTML readable format for getting/posting (eg. value=[12,21])
I have tried the following:
string[] array1 = methodToGetStringArray(); //assuming [12,21] for example
string finalString = "value="+array1; //intended output is value=[12,21]
Which of course doesn't work.
I would like to know the method to provided the value as shown above.

You can try,
string finalString = String.Format("value=[{0}]", string.Join(", ", array1));
finalString should return,
value=[12, 21]

Try like this:
string[] array1 = methodToGetStringArray();
string json = JsonConvert.SerializeObject(array1);
Refer JSON.NET

you can try this
string finalString = "Value = [" + string.Join(",", array1) + "]";

Use string.Join method:
string finalString = "value=[" + string.Join(",",array1) + "]";
Or JavaScriptSerializer:
var serializer = new JavaScriptSerializer();
var finalString = "value=" + serializer.Serialize(array1);

List<string> list = new List<string>(array1);
var a = "value=[" + list.Aggregate((x, y) => x + "," + y) + "]";

Related

How to add an element with comma to my csv?

Hello I have a code like this:
public string dataToCsv(Dictionary<string, List<string>> data, long qty, string segment)
{
string dateToday = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
string user = Environment.UserName;
var pathToCsv = "C:/Users/" + user + "/Documents/"+ segment + "-" + dateToday + ".csv";
StringBuilder sb = new StringBuilder();
String csv = String.Join(",",
data.Select(d => d.Key));
sb.Append(csv + Environment.NewLine);
for (int i = 0; i < qty; i++) {
String csv1 = String.Join(",",
data.Select(d => string.Join(",", d.Value.Skip(i).Take(1))));
sb.Append(csv1 + Environment.NewLine);
}
System.IO.File.WriteAllText(pathToCsv, sb.ToString());
return pathToCsv;
}
Works pretty fine but when an element value has a comma. That value is separated and lag the columns of the csv. I need if the element has a comma put with them in the csv. Is there any way to do this?
Maybe if I change the separator from the dictionary but donĀ“t know how to do it.
My Dictionary has a list of strings.

To return the list in JSON format

Below is my code,
List<string> modified_listofstrings = new List<string>();
string sJSON = "";
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
resulted_value = final_resulted_series_name + ":" + period_name + ":" + period_final_value;
modified_listofstrings.Add(resulted_value);
json_resultedvalue = JsonConvert.SerializeObject(resulted_value);
modified_listofstrings.Add(json_resultedvalue);
sJSON = jSearializer.Serialize(modified_listofstrings);
return sJSON;
But on following line ,
sJSON = jSearializer.Serialize(modified_listofstrings);
I am getting an error as Cannot implicitly convert type string to system.collection.generic.list
Let me fix your approach - instead of building JSON strings using your data, and then putting them into a list and trying again to serialize that, what you should do is build your data structure and then serialize it in one go.
Since I couldn't figure out the structure of the data in your post, here is an example with a different format:
public struct Person
{
public string Name;
public int Age;
public List<string> FavoriteBands;
}
The easiest way to serialize it is to use Newtonsoft JSON. If you have an object called person, then you would serialize it using
string json = JsonConvert.SerializeObject(person);
Now suppose you have a list of these objects i.e. List<Person> people = GetTheListFromSomewhere();, then you would serialize it using
string json = Newtonsoft.Json.JsonConvert.SerializeObject(people);
Go ahead and try it!
resulted_value = final_resulted_series_name + ":" + period_name + ":" + period_final_value;
This is not a valid JSON. It must have key, value format separated by comma. I guess it should be:
resulted_value = "{series_name : \"" + final_resulted_series_name + "\",period_name: \"" + period_name + "\",period_final_value: \"" + period_final_value + "\"}";
so the result should be something like this:
{series_name: "whatever_series_name_is", period_name:
"whatever_period_name_is",period_final_value:
"whatever_period_final_value_is"}

How to Replace the String in C#?

I have the string string test="http://www.test.com//web?testid=12".
I need to replace with in the string // into /.
Problem is if I use string a=test.replace("//","/") I get http:/www.test.com/web?testid=12 all with single slash(/) but I need http://www.test.com/web?testid=12.
I need only the second // nearby web, not first // near by www.
How to do this?
You can make second replace
string test="http://www.test.com//web?testid=12";
string a=test.Replace("//","/").Replace("http:/","http://");
=)
string test = #"http://www.test.com//web?testid=12";
test = test.Substring(0, test.LastIndexOf(#"//") - 1)
+ test.Substring(test.LastIndexOf(#"//")).Replace(#"//", #"/");
Or since its a Uri, you can do:
Uri uri = new Uri(test);
string newTest = uri.Scheme + #"//" + uri.Authority
+ uri.PathAndQuery.Replace(#"//",#"/");
string test="http://www.test.com//web?testid=12"
string[] test2 = test.Split('//');
string test = test2[0] + "//" + test2[1] + "/" + test2[2];
Regex.Replace(test, "[^:]//", "/");
you can use stringbuilder as well.
StringBuilder b =new StringBuilder();
b.Replace("/","//",int startindex,int count);
Simply remove one of the last slashes with String.Remove():
string test="http://www.test.com//web?testid=12";
string output = test.Remove(test.LastIndexOf("//"), 1);
var http = "http://someurl//data";
var splitindex = http.IndexOf("/") + 1;
var res = http.Substring(splitindex+1, (http.Length-1) - splitindex).Replace("//","/");
http = "http://" + res;
Or
StringBuilder strBlder = new StringBuilder();
strBlder.Append("http://someurl//data");
//use the previously used variable splitindex
strBlder.Replace("//", "/", splitindex + 1, (http.Length) - splitindex);

Concatenating IEnumerable<KeyValuePair<string,string>> values into string using Linq

Given IEnumerable<KeyValuePair<string,string>>, I'm trying to use linq to concatenate the values into one string.
My Attempt:
string path = attributes.Aggregate((current, next) => "#" + current.Key + "=" + current.Value + " and #" + next.Key + "=" + next.Value);
This produces the error:
Cannot convert expression type 'string' to return type 'KeyValuePair<string,string>'
Is there a more effiecient way to do this in linq?
The full method...
public IEnumerable<XmlNode> GetNodes(IEnumerable<KeyValuePair<string,string>> attributes) {
StateInfoXmlDocument stateInfoXmlDocument = new StateInfoXmlDocument();
string path = attributes.Aggregate((current, next) => "#" + current.Key + "=" + current.Value + " and #" + next.Key + "=" + next.Value);
string schoolTypeXmlPath = string.Format(SCHOOL_TYPE_XML_PATH, path);
return stateInfoXmlDocument.SelectNodes(schoolTypeXmlPath).Cast<XmlNode>().Distinct();
}
Is this what you're looking for?
var strings = attributes.Select(kvp => string.Format("#{0}={1}", kvp.Key, kvp.Value));
string path = string.Join(" and ", strings);
string s = String.Join("#",attributes.Select(kv=>kv.Key+"="+kv.Value));
If you want to use aggregate to make a string you need to use the seeded overload of aggregate
if you use the none seeded version then all the types in the call need to be the same.
string templ = "{0}={1}";
string _authStr = String.Join("&", formParams.Select(kv => String.Format(templ, kv.Key, kv.Value));

String: replace last ".something" in a string?

I have some string and I would like to replace the last .something with a new string. As example:
string replace = ".new";
blabla.test.bla.text.jpeg => blabla.test.bla.text.new
testfile_this.00001...csv => testfile_this.00001...new
So it doesn't matter how many ..... there are, I'd like to change only the last one and the string what after the last . is coming.
I saw in C# there is Path.ChangeExtension but its only working in a combination with a File - Is there no way to use this with a string only? Do I really need regex?
string replace = ".new";
string p = "blabla.test.bla.text.jpeg";
Console.WriteLine(Path.GetFileNameWithoutExtension(p) + replace);
Output:
blabla.test.bla.text.new
ChangeExtension should work as advertised;
string replace = ".new";
string file = "testfile_this.00001...csv";
file = Path.ChangeExtension(file, replace);
>> testfile_this.00001...new
You can use string.LastIndexOf('.');
string replace = ".new";
string test = "blabla.test.bla.text.jpeg";
int pos = test.LastIndexOf('.');
if(pos >= 0)
string newString = test.Substring(0, pos-1) + replace;
of course some checking is required to be sure that LastIndexOf finds the final point.
However, seeing the other answers, let me say that, while Path.ChangeExtension works, it doesn't feel right to me to use a method from a operating system dependent file handling class to manipulate a string. (Of course, if this string is really a filename, then my objection is invalid)
string s = "blabla.test.bla.text.jpeg";
s = s.Substring(0, s.LastIndexOf(".")) + replace;
No you don't need regular expressions for this. Just .LastIndexOf and .Substring will suffice.
string replace = ".new";
string input = "blabla.bla.test.jpg";
string output = input.Substring(0, input.LastIndexOf('.')) + replace;
// output = "blabla.bla.test.new"
Please use this function.
public string ReplaceStirng(string originalSting, string replacedString)
{
try
{
List<string> subString = originalSting.Split('.').ToList();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < subString.Count - 1; i++)
{
stringBuilder.Append(subString[i]);
}
stringBuilder.Append(replacedString);
return stringBuilder.ToString();
}
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error("[" + System.DateTime.Now.ToString() + "] " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + " :: " + System.Reflection.MethodBase.GetCurrentMethod().Name + " :: ", ex);
throw;
}
}

Categories

Resources