Reputation: 33
I tried to create a json file of mysql database and it works with the code down below but i dont know how to give them a "header" that i need to fetch data from this json with volley in android studio i need: **this is only an example to let you know which section i need , i dont need "colors" **
{
**"colors"**: [// i need this section here but with my code i couldnt
//get this.
{
"color": "black",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,255,1],
"hex": "#000"
}
}
VOLLEY in android studio does this to get data :
JSONArray jsonArray=response.getJSONArray("colors");
Heres my code in C# for creating a Json file at localhost
namespace MySqlServerDemo
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write( ListJson() );
}
// [WebMethod]
public static string ListJson()
{
DataSet ds = new DataSet();
MySqlConnection con = new MySqlConnection("server=localhost;user id=root;database=studentdetails;password=MYPASSWORD");
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from STUDENTS", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);
List<students> studentDetails = new List<students>();
studentDetails = ConvertDataTable<students>(ds.Tables[0]);
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(studentDetails);
}
public class students
{
public string firstname { get; set; }
public string surname { get; set; }
}
private static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
T item = GetItem<T>(row);
data.Add(item);
}
return data;
}
private static T GetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
foreach (DataColumn column in dr.Table.Columns)
{
foreach (PropertyInfo pro in temp.GetProperties())
{
if (pro.Name == column.ColumnName)
pro.SetValue(obj, dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}
}
}
Upvotes: 1
Views: 759
Reputation: 741
You can simply write a wrapper class like so.
public class ContainerClass {
public List<students> Students {get;set;}
}
and serialize that.
So what you would end up doing in your ListJson method is:
var studentDetails = new ContainerClass();
studentDetails.Students = ConvertDataTable<students>(ds.Tables[0]);
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(studentDetails);
Does that make sense?
Upvotes: 1