Code need to split string AND remove unwanted characters - c#

I have a page which receives a list of dates in the following format via ajax:
["2015-06-02T23:00:00.000Z","2015-06-03T23:00:00.000Z","2015-06-04T23:00:00.000Z","2015-06-05T23:00:00.000Z"]
I have written the following code to split the dates out:
string input;
using(var reader = new StreamReader(Request.InputStream)){
input = reader.ReadToEnd();
}
string [] arr = input.Split(new string[] {","},StringSplitOptions.None);
but i need to remove the "T23:00:00.000Z" from each date. Can anyone assist?

string [] arr = input.Replace("T23:00:00.000Z","").Split(new string[] {","},StringSplitOptions.None);

This looks like a JSON array of dates. In which case using Json.NET you could just do:
DateTime[] dates = JsonConvert.DeserializeObject<DateTime[]>(*date array string*);
You're then free to do what you want with the new date array.

Its look like json array of dates. Try to deserialize it with JSON.NET library (can found it in NuGet):
var jsonString = "["2015-06-02T23:00:00.000Z","2015-06-03T23:00:00.000Z","2015-06-04T23:00:00.000Z","2015-06-05T23:00:00.000Z"]";
var result = JsonConvert.Deserialize<DateTime[]>(jsonString);

Related

Better way to converting string [123,234,...] to List<int> and back

Basically, I am trying to convert what appears to be an array of integer values stored in a string type.
[123,234,345,456] // example
Currently, I am doing the following to convert string to List<int> or an int[]:
var intList = "[123,234,345,456]".Replace("[","").Replace("]","").Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).Tolist();
Perform required operations (sort, add, remove) on the list and convert it back to a string:
string.Format("[{0}]", string.Join(",", intList));
But then this got me thinking. The data that I am working with looks like JSON. Surely there must a more direct way of converting the string into an array of integers?
I looked at using JArray.Parse(string) from Newtonsoft.Json.Linq but isn't that just adding an extra layer of complexity as now I am dealing with JArray<JToken> instead of standard int[].
If anyone has a neater solution that doesn't involve adding methods, extensions or libraries I would appreciate if you can share your knowledge.
You are correct - JSON can do this for you:
using System;
using Newtonsoft.Json;
namespace Demo
{
class Program
{
static void Main()
{
string test = "[123,234,345,456]";
var result = JsonConvert.DeserializeObject<int[]>(test);
// This prints "123, 234, 345, 456"
Console.WriteLine(string.Join(", ", result));
string andBackAgain = JsonConvert.SerializeObject(result);
// This prints "[123,234,345,456]"
Console.WriteLine(andBackAgain);
}
}
}
If your intention is to parse numbers with double quotes then
string input = #"[123,234,345,456]";
string pattern = #"\d+";
var result = Regex.Replace(input, pattern, "\"$&\"");
result.Dump();
//["123","234","345","456"]
or to parse whole object inside array braces
string input = #"[123,234,345,456]";
string pattern = #"(\d+\s*,?\s*)+";
var result = Regex.Replace(input, pattern, "\"$&\"");
result.Dump();
//["123,234,345,456"]

Serialize JSON propertly

I am trying to serialize a string array into JSON and I am using Newtonsoft JSON.Net for this but the output is wrong and I don't know how to serialize it properly.
I use this code:
string[] subscriptions = new string[] { "downloads" };
string[] exclusion = new string[] { "REFRESH_CONTENT" };
var toSend = new string[][] { subscriptions, exclusion };
string json = Newtonsoft.Json.JsonConvert.SerializeObject(toSend);
And I get this result:
params: [[\"downloads\"],[\"REFRESH_CONTENT\"]]
But I need to get this result:
params: [\"[\\\"downloads\\\"]\",\"[\\\"REFRESH_CONTENT\\\"]\"]
or without escaped strings (to be sure there is no error in the line above):
params: ["[\"downloads\"]","[\"REFRESH_CONTENT\"]"]
Thanks!
Your expectations are wrong. Your toSend is an array of string arrays. And this is what the serialization produces. If you want to get an array of strings, you have to create one:
var toSend = new string[] {JsonConvert.SerializeObject(subscriptions), JsonConvert.SerializeObject(exclusion)};
string json = JsonConvert.SerializeObject(toSend);
But this way, you'll have to parse each element of the array at the receiver side.

How to convert string to string array[] in c#

i have a string variable which receives data from web the data is in the from of string like this
string output="[1,2,3,4,5,6,7,8,9,0]";
i want to convert it into a string array [] so that i can specify each element via for each loop
string output;
into
string[] out;
PS: if any predefined method is there that will also help
You can do that using Trim And Split:
var out = output.TrimStart('[').TrimEnd(']').Split(',');
But your data looks like JSON string. So, if you are dealing with JSON instead of making your own parser try using libraries that already does that such as JSON.NET.
You can use Trim functions to remove brackets and then use Split() function to get the string array that contains the substrings in this string that are delimited by elements of a specified Unicode character.
var res = output.TrimStart('[')
.TrimEnd(']')
.Split(',');
string[] arr = output.Where(c => Char.IsDigit(c)).Select(c => c.ToString()).ToArray();
output.Substring(1, output.Length - 2).Split(',');

String with strange format to array

I have this string:
string s = "[\"default\",\"direct\"]";
I want to make an array, so the final array should be this:
["default", "direct"]
What I have tried:
string[] ss = s.Split(',');
But the result is:
What you have is JSON array. You can simply deserialize it with JSON.NET (you can add it from NuGet):
string s = "[\"default\",\"direct\"]";
string[] result = JsonConvert.DeserializeObject<string[]>(s);
you can also use the JArray.
Newtonsoft.Json.Linq.JArray jsonarr = Newtonsoft.Json.Linq.JArray.Parse(jsonResult);

Building a C# tokenizer for JSON arrays that supports exceptions

I need to tokenize JSON arrays to convert them into an Object[,].
The format will be something like:
[[1,"2"],[",]",5]
which would translate into
string json = #"[[1,""2""],["",]"",5]]";
for the matrix:
1 "2"
",]" 5
What would be the easiest way to tokenize this in C# since splitting will not work as the string may contain the split character (but escaped)?
Using Json.Net
string json = #"[[1,""2""],["",]"",5]]";
var arr = JsonConvert.DeserializeObject<object[][]>(json);
or using JavaScriptSerializer
var arr = new JavaScriptSerializer().Deserialize<object[][]>(json);

Categories