【发布时间】:2019-12-12 15:56:32
【问题描述】:
我有一个不和谐的机器人,它可以从 JSON 文件中获取密钥并根据用户输入的命令返回值。我希望能够访问复杂的 JSON 键(如“charQuote”)并返回关联值(即“此处的视频游戏角色引用”)。
{
"characterKey":
{
"charName":"Video Game character name here",
"charQuote": "Video Game character quote here",
"charImageURL": "Video Game character image url here"
}
//I omitted 11 other complex objects that are similar to this one
}
其他答案如:
How do I deserialize a complex JSON object in C# .NET?
How to get Key from nested object with a Json Object and return in array?
how to get the key from json object and convert into an array?
...反序列化并将复杂对象和/或键作为数组返回。但我想从一个复杂对象返回一个键值。
在这里,我有一个用简单的 JSON 对象管理单独的 JSON 文件的类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
namespace discordbot.Modules
{
class Utilities
{
private static Dictionary<string, string> alerts;
private const string File_Path = "json files/alerts.json";
static Utilities()
{
string json = File.ReadAllText(File_Path);
var data = JsonConvert.DeserializeObject<dynamic>(json);
alerts = data.ToObject<Dictionary<string, string>>();
}
public static string GetAlert(string key) //"hello" == key
{
if (alerts.ContainsKey(key))
return alerts[key]; //returns "Hello World" which is the value
return "";
}
这个类从输入的键返回值。将使用此类的示例异步任务方法是:
[Command("test")]
public async Task HelloWorldAsync(string hello = "hello")
{
await ReplyAsync(Utilities.GetAlert(hello));
}
这是与包含复杂对象的 JSON 文件相关联的类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
namespace discordbot.Modules
{
public static class CharacterUtilities
{
//private static List<Dictionary<string, string>> QuoteAndPicture = new List<Dictionary<string, string>>();
private static Dictionary<string, string> QuoteAndPicture = new Dictionary<string, string>();
private const string File_Path = "json files/quotesandimages.json";
static CharacterUtilities()
{
if(!File.Exists(File_Path))
{
File.WriteAllText(File_Path, "");
}
string json = File.ReadAllText(File_Path);
var data = JsonConvert.DeserializeObject<dynamic>(json);
QuoteAndPicture = data.ToObject<Dictionary<string, string>>();
}
public static string GetQuoteImageName(string key)
{
if (QuoteAndPicture.ContainsKey(key)))
return QuoteAndPicture[key];
return "";
}
调用GetQuoteImageName的异步方法
[Command("ex")] [RequireOwner]
public async Task CharacterAsync(string characterContext)
{
await ReplyAsync(CharacterUtilities.GetQuoteImageName(characterContext));
}
现在,如果我调用 GetQuoteImageName 方法,我会收到错误:The type initializer for 'discordbot.Modules.CharacterUtilities' threw an exception.
所以我想知道是否有类似的方法从复杂对象返回奇异值而不是所有复杂值,类似于上面的第一个类。
【问题讨论】: