如何使用Newtonsoft在C#中反序列化JSON

2024-04-18 22:33:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段用python编写的代码,我必须在Newtonsoft JSON的帮助下将其重写为C

def getconfig():
    with open("config.json") as f:
        return json.loads(f.read())

我必须能够访问代码中的JSON元素,正如本文所示

def getcaptcha(proxy):
    while(True):
        ret = s.get("{}{}&pageurl={}"
            .format(getconfig()['host'], getconfig()['key'], getconfig()['googlekey'], getconfig()['pageurl'])).text

到目前为止,我已经想到了这个想法:

public bool GetConfig()
        {
            JObject config = JObject.Parse(File.ReadAllText("path/config.json"));

            using (StreamReader file = File.OpenText("path/config.json"))
            using (JsonTextReader reader = new JsonTextReader(file))
            {
                JObject getConfig = (JObject) JToken.ReadFrom(reader);
            }

            return true;
        }

但它似乎不起作用,因为我无法在以后的代码中访问它

GetConfig()['host']

比如说。我甚至不能控制台。写我的JSON


Tags: path代码configjsonhostreturndeffile
1条回答
网友
1楼 · 发布于 2024-04-18 22:33:57

首先,将GetConfig函数定义为:

public JObject GetConfig()
{
    return JObject.Parse(File.ReadAllText("path/config.json"));
}

然后,调用该函数并访问json文件中定义的元素,如:

JObject config = GetConfig();
string host = config.SelectToken("host").Value<string>();
string key = config.SelectToken("key").Value<string>();

相关问题 更多 >