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



我为变量strP分配了以下JSON:

{"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 以获取对象中每个数组的键和值? 这是我到目前为止尝试过的:

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; }
}

附言我想避免使用外部 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没有内置支持在(反(序列化期间重命名属性。 详情请看这里。

最新更新