如何反序列化并获取对象及其数组键值

How to deserialize and get the object and its array keys and values

我将以下 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 中获取键和值而不预先对键名进行硬编码,您可以反序列化为 Dictionary<string, List<Dictionary<string, string>>>:

var jsonObj = new JavaScriptSerializer().Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(strP);

string indent = "   ";
var sb = new StringBuilder();
foreach (var outerPair in jsonObj)
{
    sb.Append(outerPair.Key).AppendLine(":");
    outerPair.Value.SelectMany(d => d).Aggregate(sb, (s, p) => s.Append(indent).Append(p.Key).Append(" - ").AppendLine(p.Value));
}

Console.WriteLine(sb);

顺便说一下,您的 RO 类型不能用于反序列化您问题中显示的 JSON 因为它的名称 属性:

public List<Data1> _data { get; set; }

与 JSON 中的 属性 名称不同:

{"get_the_data":[ ... ] }

这些 属性 名称需要匹配,因为 JavaScriptSerializer 在(反)序列化期间没有对属性重命名的内置支持。有关详细信息,请参阅