C# – Récupération de données d’un webservices formaté en JSON

Pré requis :

Télécharger la librairie JSON.NET : http://json.codeplex.com/

 

WebService :

[WebMethod]

public string creancierAndroid()

{

Npgsql.NpgsqlConnection sqlCon = new Npgsql.NpgsqlConnection();

string ConnectionStr = System.Configuration.ConfigurationManager.AppSettings[“connexion”].ToString();

sqlCon.ConnectionString = ConnectionStr;

string req = “select c.client_numero , ad.adresse_nom  from  client c  “;

sqlCon.Open();

DataSet ds = new DataSet();

Npgsql.NpgsqlDataAdapter da = new Npgsql.NpgsqlDataAdapter(req, sqlCon);

da.Fill(ds);

sqlCon.Close();

string strDetails = “”;

if (ds.Tables[0].Rows.Count > 0)

{

strDetails += “[“;

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

{

strDetails +=

“{\”Field1\”:\”” + ds.Tables[0].Rows[i][“creancier_numero”].ToString() + “\”, \”Field2\”:\”” + ds.Tables[0].Rows[i][“adresse_nom”].ToString() + “\”},”;

}

strDetails += “]”;

strDetails = strDetails.Replace(“,]”, “]”);

}

return strDetails;

}

 

Appel du webservice avec récupération des données JSON remis dans un Datatable :

ServiceReference1.svCyrusSoapClient sv = new ServiceReference1.svCyrusSoapClient();

string resultat = sv.creancierAndroid();

DataTable dt = new DataTable();

dt = (DataTable)JsonConvert.DeserializeObject(resultat, dt.GetType());

dataGridView1.DataSource = dt;

 

 

 

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s