2017-07-11 27 views
0

我有以下的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#方法。

+0

只是出于好奇,你有什么反对使用Json.net?它非常成熟,并且是Nuget上的头号下载软件包。你正在创造**所以**为你自己做更多的工作,避免它 –

+0

没有什么真正的,但本来想这样做......但我会检查出来:)谢谢。 – Si8

+1

我认为对于大多数.Net开发人员(甚至在微软内部),Json.net被认为是“原生”json解决方案。它默认带有大量的微软模板,特别是围绕asp.net –

回答

1

如果你只是希望得到来自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没有对(de)序列化期间重命名属性的内置支持。详情请参阅here

+0

我喜欢LINQ方法。谢谢。我会测试并让你知道它是如何去的。 – Si8

+0

我得到这个错误:'Type'System.Collections.Generic.Dictionary'2 [[System.String,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b89],[System.Collections.Generic.List' 1 [[System.Collections.Generic.Dictionary'2 [[System.String,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b89],[System.String,mscorlib,Version = 4.0.0.0,Culture =中性,PublicKeyToken = b89]],mscorlib,版本= 4.0.0.0,文化=中立,PublicKeyToken = b89]],mscorlib,版本= 4.0.0.0,文化=中立,PublicKeyToken = b89]]'不支持反序列化一个数组。' – Si8

+0

@ Si8 - 如果您的实际JSON包含一个数组 - 一个由'['和']'包围的有序数值序列 - 而不是一个对象 - 一组无序的键/值对被'{'和'}'包围。你可以发布你的实际JSON吗?它比你展示的JSON更复杂吗? – dbc

相关问题