6

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?

Community
  • 1
  • 1
hermann
  • 6,237
  • 11
  • 46
  • 66

2 Answers2

7

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());
xdumaine
  • 10,096
  • 6
  • 62
  • 103
  • +1 for the fact about json not having primitive for characters, but I feel like this doesn't make sense, you shouldn't have to change your character to a string, Json.NET should have a way to convert a character. Maybe someone should bring this up to the project development team as it doesn't make a lot of sense to me. Not saying your answer doesn't make sense just that you shouldn't have to do this, the API should deal with this internally. – konkked Aug 12 '13 at 14:10
  • @CharlesKeyser I completely agree - I personally consider this a bug with the library - it should automatically do the conversion. – xdumaine Aug 12 '13 at 14:13
  • @TimBJames no worries. I am usually the one bested in the [fastest gun in the west](http://meta.stackexchange.com/questions/9731/fastest-gun-in-the-west-problem). – xdumaine Aug 12 '13 at 14:13
2

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 ( ) );
konkked
  • 3,161
  • 14
  • 19