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.
Related
I have a json as string. I want to convert it into an object. But during conversion, everything is fine, except i get an extra braces outside of the object. That is not a valid json.
string st = "{\"Category\":\"test\"}";
var someType = JsonConvert.DeserializeObject(st);
//output of someType is {{"Category": "test"}}
//expected output {"Category": "test"}
I tried "JObject.Parse()" too. But the result is the same. It adds extra braces to the object.
I want the output as an object compulsorily.
Is there anything that i'm doing wrong? Am i missing something?
In the context of what you're asking, JsonConver.DeserializeObject(st) is doing exactly what you're asking it to do. You're asking it to convert a string representation of the "object" {"Category": "test"} to a json object. The problem with your approach, is that the compiler does not know how to interpret that string as anything other than an object, so it wraps it in a JSON object.
To get the result you're looking for, without declaring a POCO (i.e. deserializing an anonymous type), you'd need to do something like this
var definition = new { Category = "" };
var data = #"{'Category':'Test'}";
var me = JsonConvert.DeserializeAnonymousType(data, definition);
Console.WriteLine(me);
Adding another solution, given what was asked for in the comments.
dynamic deserialized = JObject.Parse("{\"Category\":\"test\"}");
The strings I try to initialize with temp.Split results are always null.
G.ReadLine() is simply a "name%path" format. I also changed the encoding to unicode for certainty that there is no encoding difference between file and program.
Here is the relevant fragment:
StreamReader g = new StreamReader(path + "database.txt",Encoding.Unicode);
do
{
String temp;
temp = g.ReadLine();
//wr.WriteLine(temp);
try
{
names[ii] = temp.Split('%')[0];
Thank you for help
So now we found the route of the problem.
The instantiation of names was wrong.
Instead of
string[] names = null;
Something like
string[] names = new string[5];
must be used. The Problem here is that you have to now before how many strings the array will contain.
I recommand you to use an List of strings so something like that:
List<string> names = new List<string>();
and then use it with:
names.Add(temp.Split('%')[0]);
"name%path".Split('%')[0] returns "name"
So the problem is not Split function, but in temp which value does not have "name%path" pattern.
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);
I use reflection to iterate over my object fields. To read a field value I use
object elementValue = element.GetValue(value)
because I don't know what kind of type I will get. My object has also a field of type char[]. When I read it using GetValue(value) I receive a variable of type object{char[]}. I would like to convert it into char[]. But how can I do it? I cannot iterate over it.
Is this what you're looking for?
char[] array = (char[])elementValue;
{char[]} is not a type. Debugger displays it for convenience. It is actually char[] only. So just a cast is enough.
For example following code will be displayed as {string[]} in debugger.
object elementValue = new string[] { "asdfasd" };
Just do
char[] arr = (char[])elementValue;
I have a method that takes an ArrayList object as a parameter.
I then try to convert this arrayList into a string array but get an InvalidCastException.
The ArrayList contains a seven random numbers. As they are of the type object I am assuming it shouldnt be a problem casting it into a string.
This is the method that I have called
p.matches(winningNumber);
public void matches(ArrayList al)
{
try
{
string nameFile;
string[] winningNumber = (string[])al.ToArray(typeof(string));
Console.WriteLine("Please enter the name of the file you want to Read from");
nameFile = Console.ReadLine();
it is with the attemt at casting that I get an exception.
You are getting this exception because in order to convert to array of strings, the elements themselves must be strings as well. You can do it with LINQ, though:
string[] winningNumber = al.Cast<object>().Select(o => o.ToString()).ToArray();
To deal with nulls, replace o.ToString() with ""+o or a conditional that checks for nulls.
You just need to use Enumerable.Cast before you call ToArray
string[] winningNumber = al.Cast<string>().ToArray();
Change
string[] winningNumber = (string[])al.ToArray(typeof(string));
To
string[] winningNumber = al.Cast<object>.Select(x=> x==null ? string.Empty : x.ToString()).ToArray();
If you have some items that are not string, you can use Enumerable.OfType. It will ignore non string types.
string[] winningNumber = al.OfType<string>().ToArray();
string[] winningNumber = al.Cast<object>.Select(x=>Convert.ToString(x)).ToArray();