例如,我有一些课程:
class User
{
int Id {get; set;}
string Name {get; set;}
}
class Venue
{
int Id {get; set;}
string Adress {get; set;}
}
class Message
{
string Text {get; set;}
int FromId {get; set;}
}
我从网上获取 json:
[%user% => {id: 1, name: "Alex"}, %user% => {id: 5, name: "John"}]
我可以解析它:
var myObjects = JsonConvert.DeserializeObject<Dictionary<string, User>>(json);
但是如果有一个json:
[%user% => {id: 1, name: "Alex"}, %venue% => {id: 465, adress: "Thomas at 68th Street"}, %message% => {text: "hello", fromId: 78}]
我可以通过键 %user% = User、%venue% = Venue 等来定义类型。
但是我该如何解析呢?
提前致谢!
更新
我目前的解决方案:
private JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
};
string myJson = "{\"%user%\":{\"id\" : 5, \"name\" : \"John\"}, \"%venue%\":{\"id\" : \"5f56de\", \"adress\": \"Thomas at 68th Street\"}}";
Dictionary<string, object> dict =
JsonConvert.DeserializeObject<Dictionary<string, object>>
(myJson, _jsonSettings);
Dictionary<string, object> d = new Dictionary<string, object>();
foreach(var o in dict)
{
string json = (string)o.Value.ToString();
switch (o.Key)
{
case "%user%":
{
var v = JsonConvert.DeserializeObject<User>(json);
d.Add(o.Key, v);
break;
}
case "%venue%":
{
var v = JsonConvert.DeserializeObject<Venue>(json);
d.Add(o.Key, v);
break;
}
case "%message%":
{
var v = JsonConvert.DeserializeObject<Message>(json);
d.Add(o.Key, v);
break;
}
}
}