【发布时间】:2017-07-11 19:41:23
【问题描述】:
我将以下 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; }
}
附言我想避免使用外部 JSON 库并使用本机 C# 方法。
【问题讨论】:
-
只是出于好奇,您对使用 Json.net 有什么反对意见?它非常成熟,是 Nuget 上下载量排名第一的软件包。通过避免它,您正在为自己创造所以更多的工作
-
没什么,只是想在本地做...但我会检查一下 :) 谢谢。
-
我认为对于大多数 .Net 开发人员(甚至在 Microsoft 内部)来说,Json.net 被认为是“本机”json 解决方案。它默认附带大量 Microsoft 模板,尤其是在 asp.net 周围
-
如果我已经默认使用原生 javascriptdeserializer 并且导入 JSON.net 会破坏什么?
-
不,它不应该破坏任何东西
标签: c# json deserialization javascriptserializer