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

Como crear un ComboBox con Ext.ux.MetaForm

Este tema se lo dedico a una pregunta que yo mismo hice en el foro de la comunidad de extjs en español y que encontre la respuesta. La pregunta era la siguiente: Como llenar un combobox con el plugin Ext.ux.MetaForm ? y  aprovecho para decirles que el mismo se encarga de crear formularios pasandole los datos y estructura desde el server. Esto es realmente sencillo y util cuando tenemos una aplicacion que genera los formularios dinamicos a partir de una base de datos , XML o cualquier fichero de almacenamiento de datos.

Primero, para lograr un formulario debemos crear un JSON con un formato que el plugin logre interpretar y el mismo debe contener varias partes como:

  1. formConfig que se encarga de la configuracion del formulario.
  2. fields que sera el arreglo de campos.
  3. data que es el arreglo que tiene los datos con los cuales se van a mostrar los campos del formulario.

Como se que un ejemplo es mejor que mil palabras aqui les dejo como deberia quedar estructurado todo este json.

/*
Creamos la estructura del Formulario.
*/
$formConfig = array(
"labelAlign"=>"left"
,"columnCount"=>2
,"labelWidth"=>80
,"defaults"=>array(
"width"=>130
)
);
/*Los campos del formulario serian de esta manera y miren el tercer campo es un combo y el $store_total es el strore del combo.
*/
$store_total = array_merge($store_total,array('1' => 'La Habana', '2' => 'Ciego de Avila', '3' => 'CUBA'));


$fields = array(
array(
"name"=>"compName"
,"fieldLabel"=>"Company"
,"editor"=>array(
"allowBlank"=>false
)
)
,array(
"name"=>"compForm"
,"fieldLabel"=>"Legal Form"
,"editor"=>array(
"allowBlank"=>false
)
)
,array(
"name"=>"clientFrom"
,"fieldLabel"=>"Mi Combo"
,"editor"=>array(
"xtype"=>"combo",
"store"=> $store_total
)
));
/*El config agrupa todos los elementos anteriores*/
$config = array(
"success"=>true
,"metaData"=>array(
"fields"=>$fields
,"formConfig"=>$formConfig
)
,"data"=>array(
"compName"=>"My Company"
,"compForm"=>"Company Form"
)
);
/*Generamos el JSON y lo imprimimos*/
echo json_encode($config);
?>

Solo nos queda descargarnos el plugin e  incluirlo en la pagina html junto con las librerias de extjs y disfrutarlo.

saludos…

enero 20, 2009 at 3:38 pm Deja un comentario

Hello world!

Pensé en cambiar el titulo pero decidí dejar la bienvenida para todos los Blogueros y Blogueras que visiten mi blog. Mi objetivo es compartir algo de la experiencia adquirida en el transcurso de mis estudios y dejar que ustedes, la razón de este blog comenten, den variantes o mejores soluciones de lo que aquí  escriba.

Por hoy tengo sueño mañana les presento mi segundo post.

Adiós…

enero 19, 2009 at 6:29 am Deja un comentario


Categorías

  • Blogroll

  • Feeds