How to retrieve the values in a multi dimensional array using JSON? - c#

I have created a multi dimensional array.. which stores the table rows values from database..I need to store the array elements into json format,and should display the array elements seperately(ie,row wise as in the data base table). my code is here..but it displays all the data in json format like this. :
{"question":"6"}{"question":"mother?"}{"question":"fghh"}{"question":"bbb"}{"question":"qwe"}{"question":"wer"}{"question":"5"}{"question":"colg?"}{"question":"sdf"}{"question":"scf"}{"question":"aaa"}{"question":"dfdf"}
my code is here :
SqlDataAdapter da = new SqlDataAdapter("select question_num,q_text,answer1_text,answer2_text,answer3_text,answer4_text from question_bank_details where question_num in (select top 2 question_num from question_bank_details order by newid())", con5);
DataTable dt = new DataTable();
da.Fill(dt);
int i; int j;
string[,] array_questions = new string[dt.Rows.Count, dt.Columns.Count];
for (i = 0; i < dt.Rows.Count; i++)
{
for (j = 0; j < dt.Columns.Count; j++)
{
array_questions[i, j] = dt.Rows[i][j].ToString();
//Response.Write(array_questions[i, j]);
}
}
foreach (string question_row in array_questions)
{
var ques = new { question = question_row };
JavaScriptSerializer js = new JavaScriptSerializer();
// string json = js.Serialize(question_row);
string json = js.Serialize(ques);
Response.ContentType = "application/json";
Response.Write(json);
}
}
how can i display it row wise as in the database table ? please help ?
I need the output like this :
{"question" : "6" "mother?" "bbb" "fghhh" "bbb" "qwe" "wer"}{"question" : "5" "colg" "sdf" "scf" "aaa" "ddd" "hjk"}

If you are wanting a JSON array of objects with named properties, try the following:
var rows = dt.Rows
.Cast<DataRow>()
.Select(row => new {
ID = row[0],
Question = row[1],
Answer1 = row[2],
Answer2 = row[3],
Answer3 = row[4],
Answer4 = row[5],
})
.ToArray();
string json = js.Serialize(rows);
If instead you want an array of arrays as JSON, try this:
dt.Rows
.Cast<DataRow>()
.Select(row => new string[] {
row[0].ToString(),
row[1].ToString(),
row[2].ToString(),
row[3].ToString(),
row[4].ToString(),
row[5].ToString(),
})
.ToArray();
string json = js.Serialize(rows);
If you want something else, please update your question accordingly.

Your serializing turns the data into JSON. What you are trying to do is not JSON.
According to the information you gave you are trying to do something which isn't standard - you'll probably need to code it yourself.

Related

Why is this ArrayList duplicating he rows

I am junior developer and I am trying to populate an ArrayList from a Dictionary. My problem is rather then adding a new record to the ArrayList it adds the new record but also overwrites the values for all the other values in the array.
So if I inspect the values as the ArrayList is being populated I see the values from the Dictionary as expected. But when that row is inserted into the ArrayList all of the existing rows are over written with the data from current Dictionary Row. So I end up with an ArrayList with several rows that are a duplicate of the last record added from the dictionary. My code is shown below. Can someone please tell me what am I doing wrong? Code below
ArrayList arrData = new ArrayList();
eSummary edata = new eSummary();
//Starts with the first 50 recods retrieved and adds them to the ArrayList. Loops thru to get remaining records
while (blnEmpty)
{
if (response.IsSuccessStatusCode)
{
string json = response.Content.ReadAsStringAsync().Result;
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, dynamic>>(json);
for (int i = 0; i < dict.Values.Sum(x => x.Count); i++)
{
foreach (var item in dict)
{
string checkId = (dict["data"][i]["Id"]);
edata.Id = dict["data"][i]["Id"];
edata.idExternal = (dict["data"][i]["idExternal"]) == null ? "" : (dict["data"][i]["idExternal"]);
edata.Type = "Video";
edata.ownerId = (dict["data"][i]["uploadedByOwnerId"]);
edata.dateUploaded = Convert.ToDateTime((dict["data"][i]["dateUploaded"]));
edata.durationSeconds = Convert.ToDouble((dict["data"][i]["durationSeconds"]));
edata.category = (dict["data"][i]["categories"]).Count < 1 ? string.Empty : (dict["data"][i]["categories"][0]);
edata.title = (dict["data"][i]["title"]) == string.Empty ? string.Empty : (dict["data"][i]["title"]);
edata.dateRecordStarted = Convert.ToDateTime((dict["data"][i]["dateRecordStart"]));
edata.DateAPIRan = DateTime.Now;
if (CheckAutoTag(checkId, dict["data"][i]["tags"]))
{
edata.AutoTagged = true;
}
else edata.AutoTagged = false;
arrData.Add(edata);
edata is a reference type. You keep updating the values of a single object within the loop.
You need to call new eSummary() and set the values on the new object and then add that to your list.
But do note, you should not be using ArrayList in modern c#. Use a List<eSummary> instead.

How to convert string separated by new line and comma to DataTable in C#

I have a string like this:
"Product,Price,Condition
Cd,13,New
Book,9,Used
"
Which is being passed like this:
"Product,Price,Condition\r\Cd,13,New\r\nBook,9,Used"
How could I convert it to DataTable?
Trying to do it with this helper function:
DataTable dataTable = new DataTable();
bool columnsAdded = false;
foreach (string row in data.Split(new string[] { "\r\n" }, StringSplitOptions.None))
{
DataRow dataRow = dataTable.NewRow();
foreach (string cell in row.Split(','))
{
string[] keyValue = cell.Split('~');
if (!columnsAdded)
{
DataColumn dataColumn = new DataColumn(keyValue[0]);
dataTable.Columns.Add(dataColumn);
}
dataRow[keyValue[0]] = keyValue[1];
}
columnsAdded = true;
dataTable.Rows.Add(dataRow);
}
return dataTable;
However I don't get that "connecting cells with appropriate columns" part - my cells don't have ~ in string[] keyValue = cell.Split('~'); and I obviously get an IndexOutOfRange at DataColumn dataColumn = new DataColumn(keyValue[0]);
Based on your implementation, I have written the code for you, I have not tested it. But you can use the concept.
DataRow dataRow = dataTable.NewRow();
int i = 0;
foreach (string cell in row.Split(','))
{
if (!columnsAdded)
{
DataColumn dataColumn = new DataColumn(cell);
dataTable.Columns.Add(dataColumn);
}
else
{
dataRow[i] = cell;
}
i++;
}
if(columnsAdded)
{
dataTable.Rows.Add(dataRow);
}
columnsAdded = true;
You can do that simply with Linq (and actually there is LinqToCSV on Nuget, maybe you would prefer that):
void Main()
{
string data = #"Product,Price,Condition
Cd,13,New
Book,9,Used
";
var table = ToTable(data);
Form f = new Form();
var dgv = new DataGridView { Dock = DockStyle.Fill, DataSource = table };
f.Controls.Add(dgv);
f.Show();
}
private DataTable ToTable(string CSV)
{
DataTable dataTable = new DataTable();
var lines = CSV.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var colname in lines[0].Split(','))
{
dataTable.Columns.Add(new DataColumn(colname));
}
foreach (var row in lines.Where((r, i) => i > 0))
{
dataTable.Rows.Add(row.Split(','));
}
return dataTable;
}
You can split given string into flattened string array in one call. Then you can iterate through the array and populate list of objects.
That part is optional, since you can immediately populate DataTable but I think it's way easier (more maintainable) to work with strongly-typed objects when dealing with DataTable.
string input = "Product,Price,Condition\r\nCd,13,New\r\nBook,9,Used";
string[] deconstructedInput = input.Split(new string[] { "\r\n", "," }, StringSplitOptions.None);
List<Product> products = new List<Product>();
for (int i = 3; i < deconstructedInput.Length; i += 3)
{
products.Add(new Product
{
Name = deconstructedInput[i],
Price = Decimal.Parse(deconstructedInput[i + 1]),
Condition = deconstructedInput[i + 2]
});
}
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public string Condition { get; set; }
}
So, products collection holds 2 objects which you can easily iterate over and populate your DataTable.
Note: This requires further checks to avoid possible runtime exceptions, also it is not dynamic. That means, if you have differently structured input it won't work.
DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn(nameof(Product.Name)));
dataTable.Columns.Add(new DataColumn(nameof(Product.Price)));
dataTable.Columns.Add(new DataColumn(nameof(Product.Condition)));
foreach (var product in products)
{
var row = dataTable.NewRow();
row[nameof(Product.Name)] = product.Name;
row[nameof(Product.Price)] = product.Price;
row[nameof(Product.Condition)] = product.Condition;
dataTable.Rows.Add(row);
}

How to read the data from list object which consists of array in it

After creating the leaguelist in the code below, how can I access the values in the list in order to populate another list?
I need to pass the values of the list to another list and send it to a view.
List<Notification> notificationlist = new List<Notification>();
notificationlist.Add(new Notification { date = leaguename = leaguevenue = teamwon = })
What i am trying to do is read the values from leaguelist and I need to access the data of that list in notificationlist to populate the values for date, leaguename, leaguevenue, etc.
List<string[]> leaguelist = new List<string[]>();
while (count != 0)
{
Int16 id = Convert.ToInt16(sportds.Tables[0].Rows[count-1]["sports_details_id"].ToString());
using (SqlDataAdapter leagueDetails = new SqlDataAdapter("select league_name, league_details_venue,league_details_date from leagues, league_details where sports_details_id1 in ('" + id+ "') or sports_details_id2 in ('" + id + "')", sqlConnection1))
{
DataSet leagues = new DataSet();
leagueDetails.Fill(leagues).ToString();
lname = leagues.Tables[0].Rows[0]["league_name"].ToString();
lvenue = leagues.Tables[0].Rows[0]["league_details_venue"].ToString();
ldate = leagues.Tables[0].Rows[0]["league_details_date"].ToString();
string[] fields = new string[3];
fields[0] = lname;
fields[1] = lvenue;
fields[2] = ldate;
leaguelist.Add(fields);
}
count = count - 1}
Please help me with this !!
Based on your comment, you can walk through the list and read the values in a foreach loop and add it to the notificationList:
List<Notification> notificationlist = new List<Notification>();
foreach (string[] fields in leagueList)
{
var lname = fields[0];
var lvenue = fields[1];
var ldate = fields[2];
Console.WriteLine($"League {lname} at {lvenue} on {ldate}");
notificationsList.Add(new Notification
{
date = ldate,
leaguename = lname,
leaguevenue = lvenue
};
}
You can also use LINQ, like this:
notificationsList.AddRange(
leagueList.Select(fields => new Notificationnew Notification
{
date = fields[2],
leaguename = fields[0],
leaguevenue = fields[1]
});
This might help, you can select a single element from your list and add it to your notification list. You could use a for loop to iterate through your list and do something like this.
var s = leaguelist[0];
notificationList.Add(new Notification
{
date = s[0],
leagename = s[1],
leaguevenue = s[2]
});

Convert SQLDataReader results to JSON, with nested JSON objects

I have a C# application which retrieves an SQL result set in the following format:
customer_id date_registered date_last_purchase loyalty_points
1 2017-01-01 2017-05-02 51
2 2017-01-23 2017-06-21 124
...
How can I convert this to a JSON string, such that the first column (customer_id) is a key, and all other subsequent columns are values within a nested-JSON object for each customer ID?
Example:
{
1: {
date_registered: '2017-01-01',
date_last_purchase: '2017-05-02',
loyalty_points: 51,
...
},
2: {
date_registered: '2017-01-23',
date_last_purchase: '2017-06-21',
loyalty_points: 124,
...
},
...
}
Besides date_registered, date_last_purchase, and loyalty_points, there may be other columns in the future so I do not want to refer to these column names specifically. Therefore I have already used the code below to fetch the column names, but am stuck after this.
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
var columns = new List<string>();
for (var i = 0; i < sqlDataReader.FieldCount; i++)
{
columns.Add(sqlDataReader.GetName(i));
}
while (sqlDataReader.Read())
{
rows.Add(columns.ToDictionary(column => column, column => sqlDataReader[column]));
}
You could use something like this to convert the data reader to a Dictionary<object, Dictionary<string, object>> and then use Json.NET to convert that to JSON:
var items = new Dictionary<object, Dictionary<string, object>>();
while (sqlDataReader.Read())
{
var item = new Dictionary<string, object>(sqlDataReader.FieldCount - 1);
for (var i = 1; i < sqlDataReader.FieldCount; i++)
{
item[sqlDataReader.GetName(i)] = sqlDataReader.GetValue(i);
}
items[sqlDataReader.GetValue(0)] = item;
}
var json = Newtonsoft.Json.JsonConvert.SerializeObject(items, Newtonsoft.Json.Formatting.Indented);
Update: JSON "names" are always strings, so used object and GetValue for the keys.

Arraylist multiple dimensions C# 2.0

I am trying to create a multi dimension array
What I have so far is...
ArrayList iEFiles = (ArrayList)Session["Files"];
iEFiles.Add(Server.MapPath(FileName));
FileName = "Testing123"
FileName = "AnotherTest"
What I want it to do is have it come out like this...
FileName = ("Testing123", "Waterproof")
FileName = ("AnotherTest", "Non-Waterproof")
Like Array[,]
Any ideas?
To display the records...
BindGridview(iEFiles);
private void BindGridview(ArrayList list)
{
DataTable dt = new DataTable();
dt.Columns.Add("FileName");
dt.Columns.Add("id");
dt.Columns.Add("snFile");
int c = list.Count;
for (int i = 0; i < c; i++)
{
dt.Rows.Add();
dt.Rows[i]["FileName"] = list[i].ToString().ToUpper();
dt.Rows[i]["id"] = i;
dt.Rows[i]["snFile"] = list[i].ToString();
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
You could use the Hashtable / Dictionary to store the key value pair. If you do not want that you can make a class having two attributes FileName and Value and store object of that class in ArrayList or preferably generic List<T>.
class FileInformation
{
public FileInformation(string fileName, string value)
{
FileName = fileName;
Value = value;
}
public string FileName;
public string Value;
}
List<FileInformation> lst = new List<FileInformation>();
lst.Add(new FileInformation("fileName", "somevalue"));
An ArrayList is a bit of a .net 1.x throwback before we had generics.
You could use Dictionary<string,string> to store these values but the first item is a key and has to be unique. If you just want to store a list of 2 values you could use something like List<KeyValuePair<string,string>> or List<string[]>.

Categories