c#动态对象解决方法
本文关键字:方法 解决 对象 动态 | 更新日期: 2023-09-27 17:59:48
我有一个在.NET 4.0+中工作的代码块,但我需要在仅支持.NET 3.5的SSIS包中使用此代码。问题是我不能使用4.0以下的动态对象。我找不到变通办法,有什么想法吗?
string json = File.ReadAllText(@"C:json.txt");
dynamic deserialisedJson = JsonConvert.DeserializeObject(json);
var locations = new List<Location>();
foreach (var root in deserialisedJson)
{
foreach (var state in root)
{
foreach (var city in state)
{
foreach (var location in city)
{
Location loc = new Location();
loc.CafeId = location.First["cafeID"];
loc.CafeName = location.First["cafeName"];
loc.CafeState = location.First["cafeState"];
loc.CafeCity = location.First["cafeCity"];
loc.CafeStreetName = location.First["cafeStreetName"];
loc.CafeZip = location.First["cafeZip"];
locations.Add(loc);
}
}
}
}
更新添加JSON架构
{
"AK": {
"Anchorage": [{
"Name": "John Doe",
"Address": "123 Main St.",
"City": "Anchorage",
"State": "AK",
"Zip": "12345"
}],
"Fairbanks": [{
"Name": "Sally Smith",
"Address": "987 Main St.",
"City": "Fairbanks",
"State": "AK",
"Zip": "98765"
}]
}
}
更新2
我正在尝试IEnumerable
解决方法,但不确定正确的语法是什么,这样我就可以获取我需要的值:
string json = File.ReadAllText(@"C:json.txt");
var deserialisedJson = (IEnumerable)JsonConvert.DeserializeObject(json);
var locations = new List<Location>();
foreach (var root in deserialisedJson)
{
foreach (var state in (IEnumerable)root)
{
foreach (var city in (IEnumerable)state)
{
foreach (var location in (IEnumerable)city)
{
Location loc = new Location();
loc.Name = //What goes here???
loc.Address = //What goes here???
loc.City = //What goes here???
loc.State = //What goes here???
loc.Zip = //What goes here???
locations.Add(loc);
}
}
}
}
来自另一篇文章-Newtonsoft JSON反序列化
class MyData
{
public string t;
public bool a;
public object[] data;
public string[][] type;
}
然后使用反序列化对象的通用版本:
MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
// Do something with typeStr
}
如果没有示例json,我只能推测——但看起来您已经知道json的(相关)模式了。首先你不需要动态,即使在.net 4.0及更高版本中,我也建议不要使用它。使用dynamic
的代码通常比静态类型的代码更慢、更容易出错、更难调试,这不仅是因为编译时检查,还因为运行时错误出现得更早。
从你有限的例子来看,在不知道First
是什么的情况下,我觉得你可以做这样的事情。。。
class LocationFromJson {
public LocationContentsFromJson First;
}
class LocationContentsFromJson {
public string cafeID, cafeName, cafeState, cafeCity, cafeStreetName, cafeZip;
}
//Later usage; this should be equivalent to your example:
var deserialisedJson = JsonConvert.DeserializeObject<LocationFromJson[][][][]>(json);
var locations =
deserialisedJson //4 levels of enumerable
.SelectMany(o => o) //3 levels of enumerable
.SelectMany(o => o) //2 levels of enumerable
.SelectMany(o => o) //1 level of enumerable
.Select(o => new Location {
CafeId = o.First.cafeID,
CafeName = o.First.cafeName,
CafeState = o.First.cafeState,
CafeCity = o.First.cafeCity,
CafeStreetName = o.First.cafeStreetName,
CafeZip = o.First.cafeZip,
}).ToArray();
明确地说:这可能不变,也可能不不变。您的示例既不包括Location
的类型声明,也不包括示例json,所以我在这里推测一下:Location.CafeId
也可能是int
;我听不出你的问题。
但这应该离你需要的不太远。