我有以下代码反序列化JSON文件,然后我需要遍历字典以获取最内层的值并分配给c#对象:
public class Location
{
public string Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
string json = File.ReadAllText(@"C:\file.json");
JavaScriptSerializer ser = new JavaScriptSerializer();
var dict = ser.Deserialize<Dictionary<string, object>>(json);
foreach (var outer in dict)
{
foreach (var middle in (Dictionary<string, object>)outer.Value)
{
foreach (var inner in (ArrayList)middle.Value)
{
foreach (var loc in (Dictionary<string, object>)inner)
{
var location = new Location();
location.Id = ??;
location.Name = ??;
location.Street = ??;//...etc
}
}
}
}
当我调试并逐步执行代码时,最内层循环的值显示:
loc {[ID, 601391]} System.Collections.Generic.KeyValuePair<string,object>
Key "ID" string
Value"601391" object {string}
如何获取ID
的值并将其分配给location.Id
?
答案 0 :(得分:0)
使用内部词典中包含的KeyValuePairs的Key
和Value
:
// outer loop
// middle loop
var location = new Location();
foreach (var loc in (Dictionary<string, object>)inner) {
if (loc.Key == "ID") {
location.Id = loc.Value.ToString();
continue;
}
// if (loc.Key == "Name") ...
}
或使用索引器访问某些命名值(可能比循环遍历所有条目更快)。
// outer loop
// middle loop
var innerDict = (Dictionary<string, object>)inner;
var location = new Location();
if (innerDict.ContainsKey("ID")) {
location.Id = innerDict["ID"];
}
答案 1 :(得分:-1)
您只需要转换值并使用反射来使代码更具可读性
var props = typeof(Location).GetProperties();
string json = File.ReadAllText(@"C:\file.json");
JavaScriptSerializer ser = new JavaScriptSerializer();
var dict = ser.Deserialize<Dictionary<string, object>>(json);
foreach (var outer in dict)
{
foreach (var middle in (Dictionary<string, object>)outer.Value)
{
foreach (var inner in (ArrayList)middle.Value)
{
foreach (var loc in (Dictionary<string, object>)inner)
{
var location = new Location();
var prop = props.FirstOrDefault(p => p.Name.ToUpper() == loc.Key.ToUpper());
if (prop != null)
{
prop.SetValue(location, loc.Value);
}
}
}
}
}