ineztia
ineztia

Reputation: 825

Dapper result to json (using fastjson)

===== UPDATED 8/20/2016 =====

latest version of fastjson can now handle Dictionary<string, ?> type correctly, my problem is solved now.

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

I'm using fastjson to serialize the query result from Dapper, the table in DB has data like this:

id | name | price
1  | x    | 100
2  | y    | 200
....

And when I

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

I want the result to be:

[{"id":1,"name":"x","price":100},{"id":2,"name":"y","price":200},...]

However the actual result outputs:

[[{"Key":"id","Value":1},{"Key":"name","Value":"x"},{"Key":"price","Value":100}],
[{"Key":"id","Value":2},{"Key":"name","Value":"y"},{"Key":"price","Value":200}]...]

Lots of key-value pairs are generated which looks redundant.

Is there a way to get the correct result ?

Or should I switch to another JSON serializer ?

========== UPDATED ==========

makubex88's answer indicates that I can create a customized class mapping the table and use conn.Query<myClass> to get the correct json, though it works for this scenario, it looks like I have to create hundreds of classes for every table in DB to get ideal json result, which is indeed tiring work for me. (Thanks any way:P)

Any alternative solutions would be highly appreciated!

Upvotes: 5

Views: 8070

Answers (2)

ineztia
ineztia

Reputation: 825

I found a solution to handle it (however it may lose some efficiency), to achieve this, I write my own QueryEx method, each row in query result is an IDictionary object:

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));
}

And

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

reason: fastJSON can only parse IDictionary interface correctly, any generic versions of IDictionary will be parsed as Key-Value pair lists

Upvotes: 6

Jeric Cruz
Jeric Cruz

Reputation: 1909

Try to create a class for your output in JSON then you can serialized it in JSON.

//your class
    public class Item
    {
        int ID;
        public string Name;
        public double Price;
    }
//code:
    List<Item> = conn.Query<Item>("SELECT * FROM tableX").AsList();
    var result = Json(Item, JsonRequestBehavior.AllowGet);

Upvotes: 1

Related Questions