Posts filed under ‘ASP.net’

Convertir DataRow, DataTable y DataSet a Json

Hola a todos, como pueden ver este post se los entrego para que  comprendan como generar una cadena Json  a partir de una objeto DataRow, DataTable o DataSet de C#. Esto es importante cuando trabajamos con ajax para el intercambio de informacion entre el cliente y el servidor. Se los dejo aqui porque cuando estaba desarrollando una aplicacion se me presento ese problema y buscando en mi amigo el google encontre un sitio con una solucion a mi parecer muy buena y eficiente la cual sigo usando en mis proyectos. El sitio se los dejo aqui para que lo vean.

Luego de haber visto ese codigo y analizarlo nos dimos la tarea de generar una DLL que solo con incluirla en nuestras paginas logra convertir cualquiera de estos objetos a Json.

El modo de utilizacion es muy sencillo comienzo aqui:

La DLL se llama DataJsonConverter y despues de copiarla en la carpeta Bin o cualquier otra de nuestra aplicacion le creamos una referencia. Luego en la pagina que la usemos la incluimos using DataJsonConverter; y por ultimo la usamos de esta manera.


/*
DataBase.readQueryTable() realiza la consulta a la base de datos que retorna un DataTable */
DataTable miDataTable = DataBase.readQueryTable(query);
string jsonVar = DataJsonConverter.DataJsonConverter.Serialize(miDataTable);

Este ejemplo es con un DataTable pero de igual forma se hace para los DataSet y DataRow.

Por ultimo es necesario para el correcto funcionamiento de la DLL que se incluya en la misma carpeta de la DLL el JSON.NET( Newtonsoft.Json.dll y Newtonsoft.Json.XML).

Aqui  aparece el codigo para generar la DLL. Solo con abrir un proyecto en el Visual Studio copiar en un  fichero de codigo y compilarlo en  la carpeta bin aparecera  la DLL creada. Por supuesto que en mi caso fue DataJsonConverter pero ustedes la generan con el nombre que les paresca.



using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.IO;

namespace DataJsonConverter
{
public static class DataJsonConverter
{
private static bool FormatJsonOutput = false;

public static bool FormatOutput
{
get { return FormatJsonOutput; }
set { FormatJsonOutput = value; }
}

public static string Serialize(object value)
{
Type type = value.GetType();

Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();

json.NullValueHandling = NullValueHandling.Ignore;

json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

if (type == typeof(DataRow))
json.Converters.Add(new DataRowConverter());
else if (type == typeof(DataTable))
json.Converters.Add(new DataTableConverter());
else if (type == typeof(DataSet))
json.Converters.Add(new DataSetConverter());

StringWriter sw = new StringWriter();
Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw);
if (FormatJsonOutput)
writer.Formatting = Formatting.Indented;
else
writer.Formatting = Formatting.None;

writer.QuoteChar = ‘»‘;
json.Serialize(writer, value);

string output = sw.ToString();
writer.Close();
sw.Close();

return output;
}

public static object Deserialize(string jsonText, Type valueType)
{
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();

json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

StringReader sr = new StringReader(jsonText);
Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
object result = json.Deserialize(reader, valueType);
reader.Close();

return result;
}
}

public class DataRowConverter : JsonConverter
{
///
/// Writes the JSON representation of the object.
///
///
The to write to. ///
The value. public override void WriteJson(JsonWriter writer, object dataRow)
{
DataRow row = dataRow as DataRow;

// *** HACK: need to use root serializer to write the column value
// should be fixed in next ver of JSON.NET with writer.Serialize(object)
JsonSerializer ser = new JsonSerializer();

writer.WriteStartObject();
foreach (DataColumn column in row.Table.Columns)
{
writer.WritePropertyName(column.ColumnName);
ser.Serialize(writer, row[column]);
}
writer.WriteEndObject();
}

///
/// Determines whether this instance can convert the specified value type.
///
///
Type of the value. ///
/// true if this instance can convert the specified value type; otherwise, false.
///
public override bool CanConvert(Type valueType)
{
return typeof(DataRow).IsAssignableFrom(valueType);
}

///
/// Reads the JSON representation of the object.
///
///
The to read from. ///
Type of the object. /// The object value.
public override object ReadJson(JsonReader reader, Type objectType)
{
throw new NotImplementedException();
}
}

///
/// Converts a DataTable to JSON. Note no support for deserialization
///
public class DataTableConverter : JsonConverter
{
///
/// Writes the JSON representation of the object.
///
///
The to write to. ///
The value. public override void WriteJson(JsonWriter writer, object dataTable)
{
DataTable table = dataTable as DataTable;
DataRowConverter converter = new DataRowConverter();

writer.WriteStartObject();

writer.WritePropertyName(«Rows»);
writer.WriteStartArray();

foreach (DataRow row in table.Rows)
{
converter.WriteJson(writer, row);
}

writer.WriteEndArray();
writer.WriteEndObject();
}

///
/// Determines whether this instance can convert the specified value type.
///
///
Type of the value. ///
/// true if this instance can convert the specified value type; otherwise, false.
///
public override bool CanConvert(Type valueType)
{
return typeof(DataTable).IsAssignableFrom(valueType);
}

///
/// Reads the JSON representation of the object.
///
///
The to read from. ///
Type of the object. /// The object value.
public override object ReadJson(JsonReader reader, Type objectType)
{
throw new NotImplementedException();
}
}

///
/// Converts a object to JSON. No support for reading.
///
public class DataSetConverter : JsonConverter
{
///
/// Writes the JSON representation of the object.
///
///
The to write to. ///
The value. public override void WriteJson(JsonWriter writer, object dataset)
{
DataSet dataSet = dataset as DataSet;

DataTableConverter converter = new DataTableConverter();

writer.WriteStartObject();

writer.WritePropertyName(«Tables»);
writer.WriteStartArray();

foreach (DataTable table in dataSet.Tables)
{
converter.WriteJson(writer, table);
}
writer.WriteEndArray();
writer.WriteEndObject();
}

///
/// Determines whether this instance can convert the specified value type.
///
///
Type of the value. ///
/// true if this instance can convert the specified value type; otherwise, false.
///
public override bool CanConvert(Type valueType)
{
return typeof(DataSet).IsAssignableFrom(valueType);
}

///
/// Reads the JSON representation of the object.
///
///
The to read from. ///
Type of the object. /// The object value.
public override object ReadJson(JsonReader reader, Type objectType)
{
throw new NotImplementedException();
}
}

}

Asi termina esto.

Sadudos…..y disfrutenlo.

enero 23, 2009 at 7:23 pm Deja un comentario


Calendario

May 2024
L M X J V S D
 12345
6789101112
13141516171819
20212223242526
2728293031  

Posts by Month

Posts by Category