我的目标是能够接受任何输入并将数据添加到现有数据库中。如何在不特别声明反序列化器的情况下访问“名称”和“用户编号”属性(因为该类将根据查询而改变)?
{
"MessageType":"Sql",
"SqlCommandString":"select [name],[usernum] from x.dbo.y",
"DbReply":[
{
"name":"xx",
"usernum":22
},
{
"name":"yy",
"usernum":23
}
]
}
C#反序列化JSON:
public class SqlReply
{
public string MessageType { get; set; }
public string SqlCommandString { get; set; }
public List<object> DbReply { get; set; }
}
答案 0 :(得分:0)
您可以使用Json.Linq
:
var json = @"{
""MessageType"":""Sql"",
""SqlCommandString"":""select [name],[usernum] from x.dbo.y"",
""DbReply"":[
{
""name"":""xx"",
""usernum"":22
},
{
""name"":""yy"",
""usernum"":23
}
]
}";
var sql = JToken.Parse(json);
var replies = sql["DbReply"]
.Select(x => new
{
Name = (string)x["name"],
UserNum = (int)x["usernum"],
});
答案 1 :(得分:0)
在这里,您可以使用JavaScriptSerializer
中定义的System.Web.Extensions.dll
类来执行此操作。您可以将JSON数据反序列化为dynamic
对象:
var serializer = new JavaScriptSerializer();
dynamic obj = serializer.Deserialize(json, typeof(object));
foreach (var reply in obj["DbReply"])
{
string name = reply["name"];
int usernum = reply["usernum"];
}
或进入DbReply
:
var serializer = new JavaScriptSerializer();
SqlReply obj = serializer.Deserialize(json, typeof(SqlReply)) as SqlReply;
foreach (dynamic reply in obj.DbReply)
{
string name = reply["name"];
int usernum = reply["usernum"];
}
答案 2 :(得分:0)
感谢评论中的@stuartd建议,我将使用parse然后手动解析字符串