String with strange format to array - c#

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

Related

How to deserialize a List<float> from a JSON string?

This is my JSON string who represent just a simple List:
{"accelerationsList":"[-3.1769, 3.304, 6.3455997, 3.1701]"}
And this is my C# code to deserialize it:
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result; // i know about deadlock...
List<float> accelerationsList = new JavaScriptSerializer().Deserialize<List<float>>(jsonContent);
I dont know why my accelerationsList is empty! Any suggestions?
Use Newtonsoft.Json, it makes it clean
string accelerationsListString = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonContent)["accelerationsList"];
List<float> accelerationsList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<float>>(accelerationsListString);
you get the list of float in a string, so we need to convert the string to list after extracting
I believe you have most of what you are looking for except for 1 issue.
you are trying to convert the entire content (json string) to List. You need to convert the json object properly to get the value of accelerationsList, then convert the string that is your List of Floats properly.
string jsonContent = #"{""accelerationsList"":""[-3.1769, 3.304, 6.3455997, 3.1701]""}";
var stringRepOfArray = JObject.Parse(jsonContent)["accelerationsList"].ToString();
List<float> floatList = new JavaScriptSerializer().Deserialize<List<float>>(stringRepOfArray);
Output:
floatList
Count = 4
[0]: -3.1769
[1]: 3.304
[2]: 6.34559965
[3]: 3.1701

convert json string to string array

I'm trying to convert a json string to a string array
my json string: "[\"false\",\"true\"]"
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
string[] strArray = new string[2];
strArray = js.Deserialize("[\"false\",\"true\"]", string[2]).ToArray();
but it only allows me to do a charArray.
I just need to be able to call my result as strArray[0] so that it will return "false"
Try doing:
strArray = js.Deserialize<string[]>("[\"false\",\"true\"]");
Your example code wouldn't compile. The second parameter should be a Type object, which string[2] isn't. It should be this:
strArray = js.Deserialize("[\"false\",\"true\"]", typeof(string[]));
Or, as the other answer mentioned, you can use the other, generic overload for the method:
strArray = js.Deserialize<string[]>("[\"false\",\"true\"]");
Either one will do exactly the same thing. It's just handy to be able to pass a Type object sometimes if you don't know beforehand what the actual type will be. In this case you do, so it doesn't matter.
Why not use Newtonsoft's JArray type? It is built for this conversion and can handle many edge cases automatically.
var jArray = JArray.Parse("[\"false\",\"true\"]");
var strArray = jArray.ToObject<string[]>()
This will give you a string array. But you could also elect to use .ToArray() to convert to a JToken array which can sometimes be more useful.

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.

Code need to split string AND remove unwanted characters

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

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(',');

Categories