我的 json 文件看起来像这样
{
lab :[
{
"name": "blah",
"branch": "root",
"buildno": "2019"
}]
}
因此,我需要访问 buildno (2019( 的值并将其解析为程序中的变量。
这是我的课
public class lab
{
public string name { get; set; }
public string branch { get; set; }
public string buildno { get; set; }
}
我使用Newtonsoft.json尝试了这种方法
using (StreamReader r = new StreamReader(@"ba.json"))
{
string json2 = r.ReadToEnd();
lab item = JsonConvert.DeserializeObject<lab>(json2);
Console.WriteLine(item.buildno);
}
但我没有得到任何输出!!只有空白屏幕。
您可以使用以下函数从 json 中获取单个值。
JObject.Parse((
只需将任何 API(如果您正在使用(返回的 json 作为参数传递给 Parse 函数,并获取如下值:
// parsing the json returned by OneSignal Push API
dynamic json = JObject.Parse(responseContent);
int noOfRecipients = json.recipients;
我正在使用OneSingal API发送推送通知,并在点击他们的API时返回了一个json对象。这里的"收件人"基本上是 json 中返回的密钥。 希望这对某人有所帮助。
jsong 结构,由你给出
{
lab :[
{
"name": "blah",
"branch": "root",
"buildno": "2019"
}
}
它不是有效的json结构,应该是这样的
{
lab :[
{
"name": "blah",
"branch": "root",
"buildno": "2019"
}]
}
然后你 C# 类结构是
public class Lab
{
public string name { get; set; }
public string branch { get; set; }
public string buildno { get; set; }
}
public class RootObject
{
public List<Lab> lab { get; set; }
}
如果您这样做,那么下面的代码将起作用,或者您正在尝试的代码将起作用。
利用反序列化/序列化在 .NET 对象类型中转换您的 json:利用牛顿软件库:序列化和反序列化 JSON
例:
string json = @"{
'Email': 'james@example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine( account.Email);
首先,你创建一个 json 对象
var lab = JSON.stringify({
"name": "blah",
"branch": "root",
"buildno": "2019"
});
然后你可以像这样得到这个 JSON 对象
dynamic model = JsonConvert.DeserializeObject(lab);
然后你会得到这样的价值
lab l = new lab();
l.buildno = model.buildno;
希望这对您有所帮助。