2017-07-11 40 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

相關問題