【发布时间】:2017-10-24 16:43:42
【问题描述】:
我确定我遗漏了一些非常明显的内容,并且我已经阅读了不同的线程(例如 this 一个、this 和 this,仅列出最后几个)但我仍然找不到回答...
这是我的课程:
using System;
using Newtonsoft.Json;
namespace WebAPIClient
{
public class XWTournament
{
private string name;
[JsonProperty("name")]
public string Name { get => name; set => name = value; }
}
public class Root
{
public XWTournament xwtournam { get => xwtournam; set => xwtournam = value; }
}
}
在这里我尝试使用它们:
msg = "{\"tournament\": {\"Name\": \"Worlds 2014 Flight One\"}}";
Root root = JsonConvert.DeserializeObject<Root>(msg) ;
string pippo = root.xwtournam.Name;
但在这种情况下,我收到堆栈溢出错误...
我错过了什么?如何读取字符串中的变量?
编辑:感谢有用的答案,我以这种方式更正了代码
using System;
using Newtonsoft.Json;
namespace WebAPIClient
{
public class XWTournament
{
//I've deleted the private variable
public string Name { get; set; }
}
public class Root
{
[JsonProperty("tournament")]
public XWTournament xwtournam { get; set; }
}
}
【问题讨论】:
-
如果你使用我的代码,你可以解决你的问题
-
如果那里没有真正的功能,则不应定义 getter/setter。正如你所拥有的那样,
{ get; set; }会做同样的事情,那时你就不需要私有字段了。 -
@AmirHKH 抱歉,你的代码在哪里?
-
@jeff-skyrunner 我把它贴在下面,请使用它,如果您有任何问题,我可以解释更多
标签: c# asp.net-core json.net