我有以下的JSON赋值给变量strP
:如何反序列化和获取对象和数组键和值
{"get_the_data":[{"when_date":"09/12/2019","which_loc":"Orlando","who_witness":"visitor"}]}
,我需要生成以下的输出:
get_the_data:
when_date - 09/12/2019
which_loc - Orlando
who_witness - visitor
我如何反序列化这个JSON以获得对象内每个数组的KEY和VALUE?这是我到目前为止所尝试的:
string object1, string array1;
var jsonObj = new JavaScriptSerializer().Deserialize<RO>(strP);
//get the parent key: 'get_the_data'
object1 = get_the_data.ToString();
foreach (var p in strP._data)
{
//how can I get the KEY and the VALUE of each array within the object
array1 += p.Key + " - " + p.Value + Environment.NewLine; //e.g. when_date - 09/12/2019
}
Console.WriteLine(object1 + ":" + Environment.NewLine + array1);
//...
public class Data1
{
public string when_date { get; set; }
public string which_loc { get; set; }
public string who_witness { get; set; }
}
public class RO
{
public List<Data1> _data { get; set; }
}
p.s.我想避免使用外部JSON库并使用本机C#方法。
只是出于好奇,你有什么反对使用Json.net?它非常成熟,并且是Nuget上的头号下载软件包。你正在创造**所以**为你自己做更多的工作,避免它 –
没有什么真正的,但本来想这样做......但我会检查出来:)谢谢。 – Si8
我认为对于大多数.Net开发人员(甚至在微软内部),Json.net被认为是“原生”json解决方案。它默认带有大量的微软模板,特别是围绕asp.net –