Dapper结果为json(使用fastjson)

ine*_*tia 5 .net c# json dapper fastjson

=====更新时间2016年8月20日=====

最新版本的fastjson现在可以Dictionary<string, ?>正确处理类型,我的问题现在解决了.

=============================

我正在使用fastjson来序列化来自Dapper的查询结果,DB中的表具有如下数据:

id | name | price
1  | x    | 100
2  | y    | 200
....
Run Code Online (Sandbox Code Playgroud)

当我

using Dapper;
using fastJSON;
// ....
JSON.Parameters.KVStyleStringDictionary = false;
// ....
result = JSON.toJSON(conn.Query("SELECT * FROM tableX"));
Run Code Online (Sandbox Code Playgroud)

我希望结果如下:

[{"id":1,"name":"x","price":100},{"id":2,"name":"y","price":200},...]
Run Code Online (Sandbox Code Playgroud)

但实际结果输出:

[[{"Key":"id","Value":1},{"Key":"name","Value":"x"},{"Key":"price","Value":100}],
[{"Key":"id","Value":2},{"Key":"name","Value":"y"},{"Key":"price","Value":200}]...]
Run Code Online (Sandbox Code Playgroud)

生成了许多看起来多余的键值对.

有没有办法得到正确的结果?

或者我应该切换到另一个JSON序列化程序?

==========更新==========

makubex88的答案表明我可以创建一个映射表的自定义类,并使用它conn.Query<myClass>来获取正确的json,虽然它适用于这种情况,看起来我必须为DB中的每个表创建数百个类才能获得理想的json结果,对我来说确实很累人.(谢谢你:P)

任何替代解决方案将受到高度赞赏!

ine*_*tia 5

我找到了一个处理它的解决方案(但它可能会失去一些效率),为实现这一点,我编写了自己的QueryEx方法,查询结果中的每一行都是一个IDictionary对象:

public IEnumerable<IDictionary> QueryEx(IDbConnection conn, string sql, object argSet = null) {
    var result = conn.Query(sql, argSet) as IEnumerable<IDictionary<string, object>>;
    return result.Select(r => r.Distinct().ToDictionary(d => d.Key, d => d.Value));
}
Run Code Online (Sandbox Code Playgroud)

result = JSON.toJSON(conn.QueryEx("SELECT * FROM tableX"));
// output: [{"id":1,"name":"x","price":100},{"id":2,"name":"y","price":200},...]
Run Code Online (Sandbox Code Playgroud)

原因:fastJSON只能正确解析IDictionary接口,任何通用版本的IDictionary都会被解析为键值对列表