Building a C# tokenizer for JSON arrays that supports exceptions - c#

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

Related

Json get array object from JSON Object C#

I have this json string passed to my webapi
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";
I may have more than on pair of (K,V) inside. How do i parse this in C# ?
I thought i could first convert my string to a JObject and get the key for datamodel from that and then use JArray to parse the K,V. But its throwing a jsonreader exception on the first line of code here
JObject my_obj = JsonConvert.DeserializeObject<JObject>(jsonstring.ToString());
and then do this..
JObject data = my_obj["datamodel"].Value<JObject>();
First of all, the JSON string you are posting is not valid. Given your comment, you can clean up the quotes before and after the square brackets using this snippet:
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";;
string jsonstringCleaned = jsonstring.Replace("\"[", "[").Replace("]\"", "]");
var my_obj = JsonConvert.DeserializeObject<JObject>(jsonstringCleaned);
The code is right, but the exception you are getting is related to the formatting of your JSON string. If you put valid JSON in this code, it should work as expected.
There are \" missing around V1 in your JSON string.
It should look like this:
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";
First always make sure that you have a valid Json string. A simple way to do that is paste it into a Json to C# converter tool, such as this one: http://json2csharp.com/
It may be simpler and more readable to use single quotes within your Json string if that is an option, as it avoids the need to escape the double quotes:
string jsonstring = "{'datamodel': [{'K1':'V1','K2':'V2'}]}"
Now we deserialize the object and get the JArray. There is no need to call the ToString() on the JSON jsonstring string.
var my_obj = JsonConvert.DeserializeObject<JObject>(jsonstring);
var data = (JArray)my_obj["datamodel"];
A better and more concise way to accomplish the same result could be to just use JObject.Parse. We can accomplish the same result with just one line of code.
var data = (JArray)JObject.Parse(jsonstring)["datamodel"];

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

Convert 2D string array from ASP hidden field to multidimensional array in c#

How can i convert this string from asp hidden filed
"[['Q458','','100','85'],['Q459','TS','90','65'],['Q460','','80','15']]"
to two dimensional array in C#
i have tried .ToArray() and didn't work
You can use a String.Split() method to create the first level of arrays, then go through that array and call Split() again.
Your first delimiter is ],[ and the second one is just ,.
You will have to remove the initial [ and the final one manually ] in all arrays (both levels).
Try deserializing using JavaScriptSerializer:
var arr = hiddenField.Value;
//"[['Q458','','100','85'],['Q459','TS','90','65'],['Q460','','80','15']]" ;
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var strArray = ser.Deserialize<string[][]>(arr);
Array is now 2D string Array with values like:
'Q458','','100','85'
'Q459','TS','90','65'
'Q460','','80','15'

accessing and loading JSON arrays into a .net string[] in silverlight

If I have a simple JSON object that is written in the html document space under a script tag (that looks like below), how do I easily load it into Silverlight? I need to load each of the two arrays below into their own String[] in .NET, and it doesn't need to be dynamic as to what arrays in the Player object it loads, it will always just be those two.
Thanks!!!
Player = {
Names: ["name 1","name 2","name 3"],
Files: ["file 1","file 2","file 3"]
}
In Pseudo code:
String[] Names = Page.Javascript.Player.Names;
String[] Files = Page.Javascript.Player.Files;
Try this regex:
Player[^;,N]+Names ?: ?(\[[^\]]*\])[^F]+Files ?: ?(\[[^\]]*\])
This regual expression will match for the string above. The result groups 1 and 2 will contain your json array with the strings of Names and Files`. Check also this fiddle.
The next step is just to drop the two groups in a json parser or another regular expression and you have your strings.
If you have more Json to parse, you can use .Net Json helpers in System.Json dll
var jsonObj = (JsonObject)JsonArray.Parse("{ Names: ['name 1','name 2','name 3'], Files: ['file 1','file 2','file 3']}");
// You need to cast JsonValue in string
string[] names = (jsonObj["Names"] as JsonArray).Select(j => (string)j).ToArray();
string[] files = (jsonObj["Files"] as JsonArray).Select(j => (string)j).ToArray();
You can use DataContractJsonSerializer to convert Json in object...
See more http://msdn.microsoft.com/fr-fr/library/cc197957(v=vs.95).aspx

Categories