【问题标题】:How do I deserialize JSON in C# with Newtonsoft如何使用 Newtonsoft 在 C# 中反序列化 JSON
【发布时间】:2020-10-30 19:50:43
【问题描述】:

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

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

并且我必须能够访问代码中 JSON 的元素,就像它在这个 sn-p 中显示的那样

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']

例如。我什至不能 Console.WriteLine 我的 JSON

【问题讨论】:

  • 在 C# 中,字符串用双引号括起来,例如“host”,而不是“host”。如果你尝试 'host',你应该会得到一个编译错误。

标签: python c# .net windows performance


【解决方案1】:

首先,将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>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    相关资源
    最近更新 更多