Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not determine JSON object type for type System.Char

Tags:

c#

.net

linq

I am trying to implement a random 1 character alphanumeric JArray.

I came across this :

How can I generate random alphanumeric strings in C#?

However, I need a JArray so I tried this instead :

        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var random = new Random();
        var result = new JArray(
                    Enumerable.Repeat(chars, 1)
                                .Select(s => s[random.Next(s.Length)])
                                .ToArray());

I get a Could not determine JSON object type for type System.Char error every time.

Any ideas?

like image 973
hermann Avatar asked Aug 12 '13 13:08

hermann


2 Answers

JSON Does not have a primitive for characters - only strings, numbers, and arrays. Just add a .ToString() to turn your character into a string, which can be converted to a JSON string:

    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var random = new Random();
    var result = new JArray(
                Enumerable.Repeat(chars, 1)
                            .Select(s => s[random.Next(s.Length)].ToString())
                            .ToArray());
like image 177
xdumaine Avatar answered Nov 04 '22 14:11

xdumaine


If you are getting multiple randoms in sequence may need to change your code to generate better randoms but this will work for creating a JArray

    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var random = new Random ( );
    var result = JArray.FromObject (
                Enumerable.Repeat ( chars , 1 )
                            .Select ( s => s [ random.Next ( s.Length ) ] )
                            .ToArray ( ) );
like image 25
konkked Avatar answered Nov 04 '22 13:11

konkked