[英]How do I deserialize JSON in C# with Newtonsoft
I have a snippet of a code written in python which I have to rewrite to C# with the help of Newtonsoft JSON我有一段用 python 编写的代码片段,我必须在 Newtonsoft JSON 的帮助下将其重写为 C#
def getconfig():
with open("config.json") as f:
return json.loads(f.read())
and I have to be able to access the elements of JSON in the code just as it's shown in this snippet并且我必须能够访问代码中的 JSON 元素,就像此代码段中所示
def getcaptcha(proxy):
while(True):
ret = s.get("{}{}&pageurl={}"
.format(getconfig()['host'], getconfig()['key'], getconfig()['googlekey'], getconfig()['pageurl'])).text
So far I've come up with this idea:到目前为止,我已经提出了这个想法:
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;
}
but it doesn't seem to be working since I can't access it in further code as但它似乎不起作用,因为我无法在进一步的代码中访问它
GetConfig()['host']
for example.例如。 I can't even Console.WriteLine my JSON
我什至不能 Console.WriteLine 我的 JSON
First, define your GetConfig
function as:首先,将您的
GetConfig
函数定义为:
public JObject GetConfig()
{
return JObject.Parse(File.ReadAllText("path/config.json"));
}
then, call that function and access elements defined in the json file like:然后,调用该函数并访问 json 文件中定义的元素,例如:
JObject config = GetConfig();
string host = config.SelectToken("host").Value<string>();
string key = config.SelectToken("key").Value<string>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.