0

The problem is rather simple: I am attempting to make a discord bot and all it requires is to load up all the information about all the guilds the bot is in upon initialization.

I did not exactly attempt anything due to the fact that everything seemed completely fine. I do not want to leave this hardcoded and make an unfriendly library though, which is why I am still attempting this.

Here is what I have so far: [Json File]

{
    "Guilds": [
        {
            "ID": 561524447828246535,
            "GuildName": "TestGuild",
            "Filter": [ "words", "words2" ]
        }
    ]
}

[Extracting Class]

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using J = Newtonsoft.Json.JsonPropertyAttribute;

using System;
using System.Collections.Generic;
using System.Globalization;

namespace Cuvue.JSONManagment
{
    public static class JSONManager<Generic>
    {
        public static List<Generic> ListFromJson(string directory) => JsonConvert.DeserializeObject<List<Generic>>(directory, Converter.Settings);

        public static Generic TypeFromJson(string directory) => JsonConvert.DeserializeObject<Generic>(directory, Converter.Settings);

        public static string IntoJson(Generic type) => JsonConvert.SerializeObject(type, Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

[GuildData Class]

using J = Newtonsoft.Json.JsonPropertyAttribute;

namespace Cuvue.JSONManagment
{
    public partial class GuildData
    {
        [J("Guilds")] public Guild[] Guilds { get; set; }
    }

    public partial class Guild
    {
        [J("ID")] public long Id { get; set; }
        [J("GuildName")] public string GuildName { get; set; }
        [J("Filter")] public string[] Filter { get; set; }
    }
}

[Instantiation Point]

        private async Task Async()
        {
            Client = new DiscordSocketClient(new DiscordSocketConfig
            {
                AlwaysDownloadUsers = true,
                ConnectionTimeout = 2000,
                LogLevel = LogSeverity.Debug
            });

            Commands = new CommandService(new CommandServiceConfig
            {
                SeparatorChar = ';',
                ThrowOnError = false,
                DefaultRunMode = RunMode.Async,
                CaseSensitiveCommands = true,
                LogLevel = LogSeverity.Debug
            });

            string Token = JSONManager<BotData>.TypeFromJson(BotDataJSON).Token;

            Client.MessageReceived += ClientMessageReceived;

            await Commands.AddModulesAsync(assembly: Assembly.GetEntryAssembly(), services: null);

            Client.Ready += ClientIsReady;
            Client.Log += Logging;

            await Client.LoginAsync(TokenType.Bot, Token);
            await Client.StartAsync();

            #region Populating Lists

            //Guilds = JSONManager<GuildData>.ListFromJson(GuildDataJSON);

            #endregion

            await Task.Delay(-1);
        }

[Error Message]

'Unexpected character encountered while parsing value: G. Path '', line 0, position 0.'

Well... uhhh... I expect the JSON to deserialize into the GuildData class and apply to the GuildList List. On debugging the app crashes. Not to mention that the same happens with the attempts of receiving the Token for the bot.

Mak0Z
  • 1
  • Assuming that `GuildDataJSON` is the JSON shown in the question, your problem is that the root JSON container is a single object not am array, but `JSONManager.ListFromJson()` actually tries to deserialize a `List` not a `GuildData`. You need to do `var guildData = JSONManager.TypeFromJson(GuildDataJSON);` – dbc Aug 11 '19 at 17:14
  • Doing that seemingly gave me the same error. `Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: G. Path '', line 0, position 0.'` – Mak0Z Aug 11 '19 at 17:33
  • It works for me: https://dotnetfiddle.net/rPDOJF. Or maybe `GuildDataJSON` isn't the JSON itself, but the path name for a JSON file? If so see [Can Json.NET serialize / deserialize to / from a stream?](https://stackoverflow.com/a/17788118) and https://www.newtonsoft.com/json/help/html/DeserializeWithJsonSerializerFromFile.htm – dbc Aug 11 '19 at 17:56
  • Example of loading from a file: https://dotnetfiddle.net/S3FrvS – dbc Aug 11 '19 at 18:02
  • Can you provide a [mcve] that demos the problem? Everything seems to work OK in either https://dotnetfiddle.net/rPDOJF (deserialize from string) or https://dotnetfiddle.net/S3FrvS (deserialize from file). – dbc Aug 11 '19 at 19:34

0 Answers0