deserialize json to a generic object

1,386 views
Skip to first unread message

grendo

unread,
May 22, 2011, 8:39:15 AM5/22/11
to ServiceStack .NET Open Source REST Web Services Framework
I have serialized the results of a sql query to json like in the code
below

using (IDbCommand cmd = GetIdbCommand(con, sql))
{
cmd.CommandText = sql;
using (IDataReader reader = GetIDataReader(cmd))
{
List<dynamic> data =
Common.DataReaderToDynList(reader);
string json =
JsonSerializer.SerializeToString(data);
return json;
}
}

the dynamic object is an ExpandoObject as I do not know what fields /
table will be selected until runtime.

All that works fine and I store the json string away. My problem is
how can I deserialize this json string back into some generic type of
object I can use to itterate over the database rows/columns. eg
something like a List<Dictionary<string,object>> .

I have tried various combinations of
JsonSerializer.DeserializeFromString but no luck. Any ideas how I
could do this ?

Demis Bellot

unread,
May 22, 2011, 9:08:12 AM5/22/11
to servic...@googlegroups.com
Hi Grendo,

The JsonSerializer requires the type to know what to deserialize it back into.

If you only specify object as the type, then the JsonSerializer doesn't know what object that is and will just leave it as a string.
In which case you might as well deserialize it back into a List<Dictionary<string,string>> since it's more indicative of what it gets serialized to. From there you can deserialize the string Dictionary value to the type that you know it to be.

Here are a few links showing how you could deserialize a dynamic payload:


Hope it helps,

Cheers,

Pasha Kuznetsov

unread,
Jun 3, 2012, 8:08:15 PM6/3/12
to servic...@googlegroups.com
Demis,

If you only specify object as the type, then the JsonSerializer doesn't know what object that is and will just leave it as a string.

To a degree JSON has some type information in the format itself. Would you mind if the JsonSerializer was changed to preserve the original JSON types instead of converting everything into strings?

For example:

JsonSerializer.DeserializeFromString<<object>.
25 -> 25 // int, currently a "25" string
25.5 -> 25.5 // double, currently a "25" string
"25" -> "25" // string, same as the current behavior
{"i": 25} -> new Dictionary<string, object> { { "i", 25 } }
etc

--
Pasha 

Demis Bellot

unread,
Jun 3, 2012, 8:59:10 PM6/3/12
to servic...@googlegroups.com
I'll take a pull request if someone wants to add special support for Dictionary<string, object> as long as it doesn't bloat or affect the performance of the other code paths.

Cheers,
Reply all
Reply to author
Forward
0 new messages