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?
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());
                        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 ( ) );
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With