Wrote an endpoint that loops through a date range and for each new date it calls a Stored Procedure in SQL to collect data from that date. Basically the Results I'm getting are sales from each department in a specific store. This is how the JSON response looks :
{
"12/3/2022": [
{
"Department": "1101",
"Total $": 1887.30
},
{
"Department": "6021",
"Total $": 19.45
},
{
"Department": "6030",
"Total $": 247.33
}
],
"12/4/2022": [
{
"Department": "1101",
"Total $": 1942.62
},
{
"Department": "6021",
"Total $": 0.46
},
{
"Department": "6030",
"Total $": 488.13
}
]
}
But I'd really like to have this displayed with departments as the header. So, something like this :
{
"1101": [
{
"12/3/2022": 1887.30,
"12/4/2022": 1942.62
}
],
"6021": [
{
"12/3/2022": 19.45,
"12/4/2022": 0.46
}
],
"6030": [
{
"12/3/2022": 247.33,
"12/4/2022": 488.13
}
]
}
This is my code for collecting the data :
public HttpResponseMessage GetWeeklyStoreSummary(int appid, string fromDate, string endDate, string store)
{
ResponseHandler response = new ResponseHandler(this.Request);
WeeklyStoreSummaryHelper ws = new WeeklyStoreSummaryHelper();
try
{
string connectionString = GetConnectionString(appid);
WeeklyStoreSummaryDBAdapter db = new WeeklyStoreSummaryDBAdapter(connectionString);
DataSet result;
foreach (DateTime day in ws.EachDay(fromDate, endDate))
{
var currentDate = day.ToShortDateString();
result = db.GetWeeklySummary(currentDate, store);
response.AddTable(currentDate, result.Tables[0]);
}
string jsonResponse = response.GetJsonResponse();
return response.RequestCompleted(jsonResponse);
}
catch (ArgumentException a)
{
return response.BadRequest(a.Message);
}
catch (Exception e)
{
return response.GenericError(e.Message);
}
}
Related
I have data in provinces collection like this:
{
"_id": {
"$oid": "63dc7ff82e7e5e91c0f1cd87"
},
"province": "province1",
"districts": [
{
"district": "district1",
"sub_districts": [
{
"sub_district": "sub_district1",
"zip_codes": [
"zip_code1"
]
},
{
"sub_district": "sub_district2",
"zip_codes": [
"zip_code2"
]
},
],
},
],
}
This is how I get a list of sub_district for now:
- I search for province using Builders.Filter.
- Use foreach to get districts array (In province collection) and use if-statement to check if district equal searchDistrict.
- Get sub_districts array in that distric.
Source code:
public static List<string> MongoDbSelectSubDistrict(string searchProvince, string searchDistrict)
{
List<string> subDistrictList = new List<string>();
try
{
var provincesCollection = _db.GetCollection<BsonDocument>("provinces");
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Empty;
if (searchProvince != "")
{
var provinceFilter = Builders<BsonDocument>.Filter.Eq("province", searchProvince);
filter &= provinceFilter;
}
/*
//***Need to be revised***
if (searchDistrict != "")
{
var districtFilter = Builders<BsonDocument>.Filter.Eq("provinces.district", searchDistrict);
filter &= districtFilter;
}
*/
var queryProvinces = provincesCollection.Find(filter).ToList();
foreach (BsonDocument queryProvince in queryProvinces)
{
BsonArray districtArray = queryProvince.GetValue("districts").AsBsonArray;
foreach (BsonDocument districtDocument in districtArray)
{
string district = districtDocument.GetValue("district").ToString();
if (district == searchDistrict) //***Need to be revised***
{
BsonArray subDistrictArray = districtDocument.GetValue("sub_districts").AsBsonArray;
foreach (BsonDocument subDistrictDocument in subDistrictArray)
{
string subDistrict = subDistrictDocument.GetValue("sub_district").ToString();
subDistrictList.Add(subDistrict);
}
}
}
}
}
catch (TimeoutException ex)
{
}
return subDistrictList;
}
Is there any efficient way to get this?
This is what I want:
[
{
"sub_district": "sub_district1",
"zip_codes": [
"zip_code1"
]
},
{
"sub_district": "sub_district2",
"zip_codes": [
"zip_code2"
]
},
]
And one more question: if I want to search for sub_district in the collection, how do I get this without looping in sub_districts array?
I have a list of Json objectS that I send by API as a result :
{
"Pr": {
"ClientProfil": {
"IdClient": 67,
"FirmName": null,
"NumMember": "OPTOO111",
"FirstName": "EL MONAGI",
"LastName": "ABDELJALIL",
"Email": "jalil_monagi#yahoofr",
"Adress": "7795 10eme avenue",
"City": "Montréal",
"Province": "QC",
"Country": "CA",
"Postalcode": "H2A3B3",
"Tel": "438 995 6475",
"PreferredLanguage": "fr"
},
"Programm": {
"IdProgramm": 9,
"Designation": "OPTO",
"CreationDate": "2020-01-01T00:00:00",
"SuppressionDate": null,
"RenewDate": "2021-01-04T00:00:00",
"StartDate": null,
"IsRenewDate": true
}
}
and in the front office I use the code below
public async Task<ActionResult> Authentificate(FormCollection form)
{
HttpClient client = autentificate();
string userCodePwd = form["fCode"].ToString() + ":" + form["lPwd"].ToString();
userCodePwd = Convert.ToBase64String(Encoding.Default.GetBytes(userCodePwd));
//var decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(userCodePwd));
HttpResponseMessage response = client.GetAsync("api/Login/FindPolice?userCodePasswordArray=" + userCodePwd).Result;
try
{
if (response.IsSuccessStatusCode)
{
string Result = await response.Content.ReadAsStringAsync();
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
dynamic dobj = jsonSerializer.Deserialize<dynamic>(Result);
int StatusCode = (int)response.StatusCode;
if (StatusCode==200) // Existe une assurance pour le client
{
int StatusRequest = dobj["StatusRequest"];
if (StatusRequest==1001)
{
int IdProgram = dobj["IdProgram"];
RootAQII.Profil= JsonConvert.DeserializeObject<Profil>(dobj["Pr"].ToString());
RootAQII.Programm= JsonConvert.DeserializeObject<List<Programm>>(dobj["Programm"].ToString());
if (IdProgram==9)
{
return RedirectToAction("Index", "OPTO");
}
}
}
}
else
{
}
}
catch (Exception e)
{
String message = e.Message;
}
return View();
}
the problem is when I try to parse the result of response for RootOPTOASSURED.Profil
I get this message error :
unexpected character encountered while parsing value: s. path '', line
0, position 0.
there is anyone who has any idea And thanks you in advance :)
Assuming that Result is the json string from above, the line
int IdProgram = dobj["IdProgram"];
Should fail as the only element of dobj should be dobj["PR"]
Besides that you are trying to deserialize a list of Programm entries from a single JSON entry. If Programm is supposed to be a list, than is should appear in []
{
"Pr": {
"ClientProfil": {
"IdClient": 67,
"FirmName": null,
"NumMember": "OPTOO111",
"FirstName": "EL MONAGI",
"LastName": "ABDELJALIL",
"Email": "jalil_monagi#yahoofr",
"Adress": "7795 10eme avenue",
"City": "Montréal",
"Province": "QC",
"Country": "CA",
"Postalcode": "H2A3B3",
"Tel": "438 995 6475",
"PreferredLanguage": "fr"
},
"Programm":
[
{
"IdProgramm": 9,
"Designation": "OPTO",
"CreationDate": "2020-01-01T00:00:00",
"SuppressionDate": null,
"RenewDate": "2021-01-04T00:00:00",
"StartDate": null,
"IsRenewDate": true
}
]
}
}
Either that or change the line
RootAQII.Programm= JsonConvert.DeserializeObject<List<Programm>>(dobj["Programm"].ToString());
to
RootAQII.Programm= JsonConvert.DeserializeObject<Programm>(dobj["Programm"].ToString());
I have put an example at rextester
I have a requirement to delete the data inside JSON file. I have tried so many way but it is not deleting the data. I have also tried this example.
Remove JSON objects from a large file
But in above example they are passing a jsonstring but I have a jobject type of data.
My JSON File is as following.
{
"id": 123,
"name": "Pankaj Kumar",
"address": {
"street": "El Camino Real",
"city": "San Jose",
"zipcode": 95014
},
"experiences": [
{
"companyid": 1,
"companyname": "abc1"
},
{
"companyid": 20,
"companyname": "Genpact Headstrong"
},
{
"companyid": 71,
"companyname": "new company"
},
{
"companyid": 77,
"companyname": "Mind Tree LTD"
},
{
"companyid": 89,
"companyname": "TCS"
},
{
"companyid": 22,
"companyname": "Hello World LTD"
}
],
"phoneNumber": 9988664422,
"role": "Developer"
}
I want to delete company based on companyid.
I have tried following code to delete based on company id.
private void DeleteCompany() {
var json = File.ReadAllText(jsonFile);
try {
var jObject = JObject.Parse(json);
JArray experiencesArrary = (JArray) jObject["experiences"];
Console.Write("Enter Company ID to Delete Company : ");
var companyId = Convert.ToInt32(Console.ReadLine());
if (companyId > 0) {
var companyName = string.Empty;
foreach(var company in experiencesArrary.Where(obj => obj["companyid"].Value < int > () == companyId)) {
companyName = Convert.ToString(company["companyname"]);
}
var companyToDeleted = "{ 'id': " + companyId + ", 'companyname': '" + companyName + "'}";
experiencesArrary.Remove(companyToDeleted);
jObject["experiences"] = experiencesArrary;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(jsonFile, output);
} else {
Console.Write("Invalid Company ID, Try Again!");
UpdateCompany();
}
} catch (Exception) {
throw;
}
}
Please suggest or modify my code which delete the data.
There is no need for creating deleteObject like you are doing, you are very close to solution.You can simply find your object like this and remove.
var companyToDeleted = experiencesArrary.Where(obj => obj["companyid"].Value<int>() == companyId).ToList();
foreach (var item in companyToDeleted)
{
experiencesArrary.Remove(item);
}
Update
var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["companyid"].Value<int>() == companyId);
experiencesArrary.Remove(companyToDeleted);
I am working with a Datatables.Net plug into an internal web application to my company.
The issue Im facing is in the variable JSON, I can see that I have returned a JSON response, and it is valid according to JSONLint, but I cannot get the information out of the JSON array into my tables despite following all the examples on Datatables and searching their help site.
please see my code and let me know why this isn't populating the tables.
function populateTable(json, tableId) {
var id = 'table_' + tableId;
console.log("Columns In");
//console.log("table id: " + id + " JSON Response: " + json);
try {
var table = $('#' + id).DataTable({
"data": json.d,
"deferRender": true,
"columns:": [
{ "data ": "CaseHandlerStaffNumber" },
{ "data ": "RiskProfileText" },
{ "data ": "AssignedCheckerStaffNumber" },
{ "data ": "FeedbackUserStaffNumber" },
{ "data ": "ComplaintRef" },
{ "data ": "ChildComplaintRef" },
{ "data ": "CaseTypeText" },
{ "data ": "CheckGrade" }
]
});
} catch (e) {
}
try {
table.columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
});
} catch (e) {
console.log("Error detected: " + e);
console.log(e);
}
}
-- edit --
this is an example of my JSON data.
{
"data": [{
"CaseHandlerStaffNumber": "12345678",
"RiskProfileText": "Low Risk FOS",
"AssignedCheckerStaffNumber": "77665544",
"FeedbackUserStaffNumber": null,
"ComplaintRef": "999999",
"ChildComplaintRef": "2333",
"CaseTypeText": "FOS Submission",
"CheckGrade": "Ungraded"
}]
}
also, this is how I am producing the JSON
[System.Web.Services.WebMethod()]
public static object GetDataTables(string checkId, int userId)
{
List<string> listOfColumnns = new List<string>();
listOfColumnns.Add("CaseHandlerStaffNumber");
listOfColumnns.Add("RiskProfileText");
listOfColumnns.Add("AssignedCheckerStaffNumber");
listOfColumnns.Add("FeedbackUserStaffNumber");
listOfColumnns.Add("ComplaintRef");
listOfColumnns.Add("ChildComplaintRef");
listOfColumnns.Add("CaseTypeText");
listOfColumnns.Add("CheckGrade");
int checkStatusId = Convert.ToInt32(checkId.Replace("hidJson_tbl_", ""));
TeamChecks tc = new TeamChecks();
DataTable dtMc = default(DataTable);
dtMc = tc.Get_DatatableFor_GridView(userId, checkStatusId);
DataTable dt = new DataTable();
foreach (void colName_loopVariable in listOfColumnns) {
colName = colName_loopVariable;
dt.Columns.Add(string.Format("{0}", colName));
}
foreach (void row_loopVariable in dtMc.Rows) {
row = row_loopVariable;
dt.Rows.Add(row("CaseHandlerStaffNumber"), row("RiskProfileText"), row("AssignedCheckerStaffNumber"), row("FeedbackUserStaffNumber"), row("ComplaintRef"), row("ChildComplaintRef"), row("CaseTypeText"), row("CheckGrade"));
}
string jsonResult = null;
jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
jsonResult = jsonResult.Replace("[{", "{\"data\" :[{").Replace("}]", "}]}");
return jsonResult;
}
First, make sure you remove extra space at the end of "data" property, e.g.
{ "data": "caseHandlerStaffNumber" },
If your data is in a form of array of objects you need to use "title" property as defined here https://datatables.net/examples/data_sources/js_array.html e.g.
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Office" },
{ title: "Extn." },
{ title: "Start date" },
{ title: "Salary" }
]
} );
If you're using nuget package, it internally uses Json.NET serializer with an option to lower case first letter of the data set. So, you just need to use lower case when specifying data as follows:
{ "data": "caseHandlerStaffNumber" },
{ "data": "riskProfileText" },
{ "data": "assignedCheckerStaffNumber" },
{ "data": "feedbackUserStaffNumber" },
{ "data": "complaintRef" },
{ "data": "childComplaintRef" },
{ "data": "caseTypeText" },
{ "data": "checkGrade" }
I have two DataTable, RCPT_HEADER and RCPT_DETAIL and trying to serialize into json object hierarchy using Json.NET / C#.
I've already tried code
static JArray DataToArray(string connString, string query)
{
JArray jArray = new JArray();
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int fieldcount = reader.FieldCount;
object[] values = new object[fieldcount];
reader.GetValues(values);
JObject jo = new JObject();
for (int index = 0; index < fieldcount; index++)
{
jo.Add(reader.GetName(index).ToString(), values[index].ToString());
}
jArray.Add(jo);
}
reader.Close();
}
}
}
catch (SqlException e)
{
WriteLog("[DataToArray]: " + e.Message);
}
return jArray;
}
and
static void Main(string[] args)
{
try
{
Hashtable config = getSettings(AppPath() + "mware.config");
string connString = config["cs"].ToString();
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;
JObject jObject = new JObject();
JArray jArray = new JArray();
jObject.Add("RCPT_HEADER", DataToArray(connString, "SELECT * FROM RCPT_HEADER"));
jObject.Add("RCPT_DETAIL", DataToArray(connString, "SELECT * FROM RCPT_DETAIL"));
jObject.WriteTo(jsonWriter);
Console.WriteLine(jObject.ToString());
Console.ReadLine();
}
catch (Exception e)
{
WriteLog("[postJSON]: " + e.Message);
}
}
but I'm gettin output like this:
{
"RCPT_HEADER": [
{
"RECORD_ID": "1",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM"
}
],
"RCPT_DETAIL": [
{
"RECORD_ID": "1",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"LINK_ID": "1",
"ITEM": "SKU00048700007683",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM"
},
{
"RECORD_ID": "2",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"LINK_ID": "1",
"ITEM": "SKU00048700007684",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM"
}
]
}
Actually, I would like it to return the output like this:
{
"RCPT_HEADER": [
{
"RECORD_ID": "1",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM",
"RCPT_DETAIL": [
{
"RECORD_ID": "1",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"LINK_ID": "1",
"ITEM": "SKU00048700007683",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM"
},
{
"RECORD_ID": "2",
"ACTION_CODE": "SAVE",
"CONDITION": "Ready",
"LINK_ID": "1",
"ITEM": "SKU00048700007684",
"DATE_TIME_STAMP": "9/11/2015 12:00:00 AM"
}
]
}
]
}
Any help would be greatly appreciated as this is the first time I have tried to use JSON.NET.
As you are using data tables, it will serialize tables this way as a JSON array of tables.
You can write your own JsonConverter in order to serialize it your way. Here is a good article.
However, in my opinion, there is another good but hacky solution: if you always have the same structure and it is not requiring too much performance, it will be easier to deserialize it again, move this object and serialize it back.
Something like this:
string json = "YOUR_JSON_RESULT";
JObject jsonObject = JObject.Parse(json);
((JObject)jsonObject["RCPT_HEADER"][0])
.Properties()
.Last()
.AddAfterSelf(new JProperty("RCPT_DETAIL", jsonObject["RCPT_DETAIL"]));
jsonObject.Remove("RCPT_DETAIL");
string jsonResult = jsonObject.ToString();
There is another one solution which is elegant and sounds proper. You use data tables but you need it to become serialized like it is not a table by implementing custom serializers or modificators. Probably, you just don't need data tables.
Do not use it if possible - use your own classes instead, so that you can describe any nesting and serialization order:
public class RcptDetail
{
public string RECORD_ID { get; set; }
/* ... */
}
public class RcptHeader
{
public string RECORD_ID { get; set; }
/* ... */
public RcptDetail RCPT_DETAIL { get; set; }
}