public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; if (!string.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { var enumerable = Data as IEnumerable; if (enumerable != null) { Data = new {d = enumerable}; } var serializer = new JavaScriptSerializer(); response.Write(serializer.Serialize(Data)); } }
static void Main(string[] args) { StreamReader sr = new StreamReader(Console.OpenStandardInput()); string input = sr.ReadToEnd(); sr.Dispose(); JavaScriptSerializer ser = new JavaScriptSerializer(); dynamic json = ser.DeserializeObject(input); for (int i = 1; i < json.Length; i++) { dynamic block = json[i]; string blockType = block[0]; Dictionary<string, object> blockAttr = block[1]; for (int j = 2; j < block.Length; j++) { dynamic span = block[j]; string spanType = span[0]; string text = span[1]; Console.Write(text); } Console.WriteLine(); Console.WriteLine(); } }
protected void Page_Load(object sender, EventArgs e) { // Ensure config file is setup if (!File.Exists(Server.MapPath(ConfigFile))) { throw new Exception("Config file not found"); } var serializer = new JavaScriptSerializer(); string jsonText = System.IO.File.ReadAllText(Server.MapPath(ConfigFile)); Config = serializer.Deserialize<Dictionary<string, dynamic>>(jsonText); if (Config["username"] == "your_api_username") { throw new Exception("Please configure your username, secret and site_id"); } ObjHd4 = new Hd4(Request, ConfigFile); // Models example : Get a list of all models for a specific vendor Response.Write("<h1>Nokia Models</h1><p>"); if (ObjHd4.DeviceModels("Nokia")) { Response.Write(ObjHd4.GetRawReply()); } else { Response.Write(ObjHd4.GetError()); } Response.Write("</p>"); }
/// <summary> /// 获取当前菜单,如果菜单不存在,将返回null /// </summary> /// <param name="accessToken"></param> /// <returns></returns> public static GetMenuResult GetMenu(string accessToken) { var url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", accessToken); var jsonString = HttpUtility.RequestUtility.HttpGet(url, Encoding.UTF8); //var finalResult = GetMenuFromJson(jsonString); GetMenuResult finalResult; JavaScriptSerializer js = new JavaScriptSerializer(); try { var jsonResult = js.Deserialize<GetMenuResultFull>(jsonString); if (jsonResult.menu == null || jsonResult.menu.button.Count == 0) { throw new WeixinException(jsonResult.errmsg); } finalResult = GetMenuFromJsonResult(jsonResult); } catch (WeixinException ex) { finalResult = null; } return finalResult; }
public string SearchBooks(string paramList) { JavaScriptSerializer jsonObj = new JavaScriptSerializer(); string[] parameters = paramList.Split(','); string genre = ""; var publisher = ""; if (parameters.Length > 0) { genre = parameters[0]; } if (parameters .Length > 0) { publisher = parameters[1]; } var books = new List<Book>();; try { var booksDAL = new BookSearchDAL(); books = booksDAL.SearchBooksAndUpdateHits(genre, publisher); } catch (Exception) { } return (jsonObj.Serialize(books)); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) LoadCategoryDiv(); string IPAdd = string.Empty; IPAdd = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(IPAdd)) { IPAdd = Request.ServerVariables["REMOTE_ADDR"]; //lblIPBehindProxy.Text = IPAdd; } string JSON = GetLocation(IPAdd); if (!string.IsNullOrWhiteSpace(JSON)) { JavaScriptSerializer Serializer = new JavaScriptSerializer(); dynamic dynamicResult = Serializer.Deserialize<dynamic>(JSON); //Response.Write(dynamicResult["countryName"].ToString()); //Response.Write(dynamicResult["countryCode"].ToString()); //Response.Write(dynamicResult["city"].ToString()); //Response.Write(dynamicResult["region"].ToString()); //Response.Write(dynamicResult["latitude"].ToString()); //Response.Write(dynamicResult["longitude"].ToString()); currentLocation.InnerText = string.Format(" / Country: {0}/{1}, City: {2}/{3} ", dynamicResult["countryName"].ToString(), dynamicResult["countryCode"].ToString(), dynamicResult["city"].ToString(), dynamicResult["region"].ToString()); strcurrentLocation = string.Format(" / Country: {0}/{1}, City: {2}/{3} ", dynamicResult["countryName"].ToString(), dynamicResult["countryCode"].ToString(), dynamicResult["city"].ToString(), dynamicResult["region"].ToString()); if (Session["Location"] == null) Session.Add("Location", dynamicResult["city"].ToString()); } else { string userHostIpAddress = IPAdd; // "117.197.193.243"; IPAddress ipAddress; //Response.Write("<script>alert('"+userHostIpAddress+"')</Script>"); if (userHostIpAddress == "::1") { userHostIpAddress = "117.197.193.243"; } if (IPAddress.TryParse(userHostIpAddress, out ipAddress)) { string country = ipAddress.Country(); // return value: UNITED STATES string iso3166TwoLetterCode = ipAddress.Iso3166TwoLetterCode(); // return value: US currentLocation.InnerText = string.Format("Country: {0} / Location: {1} ", country, iso3166TwoLetterCode); strcurrentLocation = string.Format("Country: {0} / Location: {1} ", country, iso3166TwoLetterCode); if (Session["Location"] == null) Session.Add("Location", iso3166TwoLetterCode); //Session.Add("Location", "wyoming"); } } }
public ActionResult Login() { var lists = ManageNodes(); var serializer = new JavaScriptSerializer(); ViewBag.Nodes = serializer.Serialize(lists); return View(); }
/// <summary> /// Parses the JSON data returned by the 0/data/getTrades.php method /// </summary> public static List<MtGoxTrade> getObjects(string jsonDataStr) { List<MtGoxTrade> tradeList = new List<MtGoxTrade>(); string json = jsonDataStr; var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); dynamic obj = serializer.Deserialize(json, typeof(object)); for (int i = 0; i < obj.Length; i++) { MtGoxTrade trade = new MtGoxTrade(); trade.date = obj[i].date; trade.price = Double.Parse(obj[i].price); trade.amount = Double.Parse(obj[i].amount); trade.price_int = Int64.Parse(obj[i].price_int); trade.amount_int = Int64.Parse(obj[i].amount_int); trade.tid = obj[i].tid; if (Enum.IsDefined(typeof(MtGoxCurrencySymbol), obj[i].price_currency)) trade.price_currency = (MtGoxCurrencySymbol)Enum.Parse(typeof(MtGoxCurrencySymbol), obj[i].price_currency, true); trade.item = obj[i].item; if (Enum.IsDefined(typeof(MtGoxTradeType), obj[i].trade_type)) trade.trade_type = (MtGoxTradeType)Enum.Parse(typeof(MtGoxTradeType), obj[i].trade_type, true); trade.primary = obj[i].primary; tradeList.Add(trade); if (i > 100) break; } return tradeList; }
public void loadVentas() { List<Venta> lv = new List<Venta>(); var javaScriptSerializer = new JavaScriptSerializer(); string jsonVentas = ""; Ventas serv = new Ventas(); serv.Url = new Juddi().getServiceUrl("Ventas"); jsonVentas = serv.getVentas((int)Session["Id"]); lv = javaScriptSerializer.Deserialize<List<Venta>>(jsonVentas); DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[7] { new DataColumn("id", typeof(int)), new DataColumn("tipo", typeof(string)), new DataColumn("autor",typeof(string)), new DataColumn("estado",typeof(string)), new DataColumn("fechafin",typeof(string)), new DataColumn("pujamax",typeof(int)), new DataColumn("pujar",typeof(string)) }); for (int i = 0; i < lv.Count; i++) { dt.Rows.Add(lv[i].id, lv[i].tipo, lv[i].autor, lv[i].estado, lv[i].fecha_F, lv[i].precio, "Pujar"); } GridView1.DataSource = dt; GridView1.DataBind(); }
private void CreateIncident() { WebClient client = new WebClient(); client.Headers[HttpRequestHeader.Accept] = "application/json"; client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.UploadStringCompleted += (object source, UploadStringCompletedEventArgs e) => { if (e.Error != null || e.Cancelled) { Console.WriteLine("Error" + e.Error); Console.ReadKey(); } }; JavaScriptSerializer js = new JavaScriptSerializer(); TriggerDetails triggerDetails = new TriggerDetails(Component, Details); var detailJson = js.Serialize(triggerDetails); //Alert name should be unique for each alert - as alert name is used as incident key in pagerduty. string key = ConfigurationManager.AppSettings["PagerDutyServiceKey"]; if (!string.IsNullOrEmpty(EscPolicy)) { key = ConfigurationManager.AppSettings["PagerDutySev1ServiceKey"]; } if (string.IsNullOrEmpty(key)) { key = ConfigurationManager.AppSettings["PagerDutyServiceKey"]; } Trigger trigger = new Trigger(key,AlertName,AlertSubject,detailJson); var triggerJson = js.Serialize(trigger); client.UploadString(new Uri("https://events.pagerduty.com/generic/2010-04-15/create_event.json"), triggerJson); }
public static List<DeepBlue.Models.Entity.DealClosingCostType> GetDealClosingCostTypesFromDeepBlue(CookieCollection cookies) { // Admin/DealClosingCostTypeList?pageIndex=1&pageSize=5000&sortName=Name&sortOrder=asc List<DeepBlue.Models.Entity.DealClosingCostType> dealClosingCostTypes = new List<DeepBlue.Models.Entity.DealClosingCostType>(); // Send the request string url = HttpWebRequestUtil.GetUrl("Admin/DealClosingCostTypeList?pageIndex=1&pageSize=5000&sortName=Name&sortOrder=asc"); HttpWebResponse response = HttpWebRequestUtil.SendRequest(url, null, false, cookies, false, HttpWebRequestUtil.JsonContentType); if (response.StatusCode == System.Net.HttpStatusCode.OK) { using (Stream receiveStream = response.GetResponseStream()) { // Pipes the stream to a higher level stream reader with the required encoding format. using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { string resp = readStream.ReadToEnd(); if (!string.IsNullOrEmpty(resp)) { JavaScriptSerializer js = new JavaScriptSerializer(); FlexigridData flexiGrid = (FlexigridData)js.Deserialize(resp, typeof(FlexigridData)); foreach (Helpers.FlexigridRow row in flexiGrid.rows) { DeepBlue.Models.Entity.DealClosingCostType dealClosingType = new DeepBlue.Models.Entity.DealClosingCostType(); dealClosingType.DealClosingCostTypeID = Convert.ToInt32(row.cell[0]); dealClosingType.Name = Convert.ToString(row.cell[1]); dealClosingCostTypes.Add(dealClosingType); } } else { } response.Close(); readStream.Close(); } } } return dealClosingCostTypes; }
public override void Execute(RequestContext context) { JavaScriptSerializer jss = new JavaScriptSerializer(); var json = jss.Serialize(paraObj); context.HttpContext.Response.Write(json); context.HttpContext.Response.ContentType = "application/json"; }
public string HandleCommand(string commandId, string body) { var serializer = new JavaScriptSerializer(); switch (commandId) { case GetTestCasesCommand: IProjectEntry projEntry; if (_analyzer.TryGetProjectEntryByPath(body, out projEntry)) { var testCases = GetTestCases(projEntry); List<object> res = new List<object>(); foreach (var test in testCases) { var item = new Dictionary<string, object>() { { Serialize.Filename, test.Filename }, { Serialize.ClassName, test.ClassName }, { Serialize.MethodName, test.MethodName }, { Serialize.StartLine, test.StartLine}, { Serialize.StartColumn, test.StartColumn}, { Serialize.EndLine, test.EndLine }, { Serialize.Kind, test.Kind.ToString() }, }; res.Add(item); } return serializer.Serialize(res.ToArray()); } break; } return ""; }
public static string MakeRequest(string url, object data) { var ser = new JavaScriptSerializer(); var serialized = ser.Serialize(data); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; //request.ContentType = "application/json; charset=utf-8"; //request.ContentType = "text/html; charset=utf-8"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = serialized.Length; /* StreamWriter writer = new StreamWriter(request.GetRequestStream()); writer.Write(serialized); writer.Close(); var ms = new MemoryStream(); request.GetResponse().GetResponseStream().CopyTo(ms); */ //alternate method ASCIIEncoding encoding = new ASCIIEncoding(); byte[] byte1 = encoding.GetBytes(serialized); Stream newStream = request.GetRequestStream(); newStream.Write(byte1, 0, byte1.Length); newStream.Close(); return serialized; }
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); return type == typeof(object) ? new DynamicJsonObject(dictionary) : null; }
public ActionResult About(string searchString) { if(searchString=="" || searchString==null) { searchString = "Jurasic Park"; } List<Movie> mo = new List<Movie>(); string responseString = ""; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:51704/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.GetAsync("api/movie?name=" + searchString).Result; if (response.IsSuccessStatusCode) { responseString = response.Content.ReadAsStringAsync().Result; } } string jsonInput=responseString; // System.Console.Error.WriteLine(responseString); JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); mo= jsonSerializer.Deserialize<List<Movie>>(jsonInput); return View(mo); }
public string CheckAvailability(string userName) { try { using (SqlConnection sqlDBConnection = new SqlConnection(ConnectionString)) { StringBuilder sqlstmt = new StringBuilder("select EmployeeID, EmployeeName from [dbo].[EmployeeDB] where EmployeeName = @userName COLLATE Latin1_General_CS_AS "); //sqlstmt.Append(Convert.ToString(userid)); SqlCommand myCommand = new SqlCommand(sqlstmt.ToString(), sqlDBConnection); myCommand.CommandType = CommandType.Text; myCommand.Parameters.AddWithValue("@userName", userName); bool foundRecord = false; sqlDBConnection.Open(); using (SqlDataReader myReader = myCommand.ExecuteReader()) { if (myReader.Read()) foundRecord = true; myReader.Close(); } sqlDBConnection.Close(); object jsonObject = new { available = (!foundRecord) }; var json = new JavaScriptSerializer().Serialize(jsonObject); return json.ToString(); } } catch (Exception ex) { return string.Format("Exception : {0}", ex.Message); } }
public static TestCaseInfo[] GetTestCases(string data) { var serializer = new JavaScriptSerializer(); List<TestCaseInfo> tests = new List<TestCaseInfo>(); foreach (var item in serializer.Deserialize<object[]>(data)) { var dict = item as Dictionary<string, object>; if (dict == null) { continue; } object filename, className, methodName, startLine, startColumn, endLine, kind; if (dict.TryGetValue(Serialize.Filename, out filename) && dict.TryGetValue(Serialize.ClassName, out className) && dict.TryGetValue(Serialize.MethodName, out methodName) && dict.TryGetValue(Serialize.StartLine, out startLine) && dict.TryGetValue(Serialize.StartColumn, out startColumn) && dict.TryGetValue(Serialize.EndLine, out endLine) && dict.TryGetValue(Serialize.Kind, out kind)) { tests.Add( new TestCaseInfo( filename.ToString(), className.ToString(), methodName.ToString(), ToInt(startLine), ToInt(startColumn), ToInt(endLine) ) ); } } return tests.ToArray(); }
public RootObjectOut GetMessageByUser(UserIn jm) { RootObjectOut output = new RootObjectOut(); String jsonString = ""; try { String strConnection = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString; SqlConnection Connection = new SqlConnection(strConnection); String strSQL = string.Format("SELECT message FROM messages WHERE msgTo = '{0}' AND [msgID] = (SELECT MAX(msgID) FROM messages WHERE msgTo='{1}')", jm.user.ToString(),jm.user.ToString()); SqlCommand Command = new SqlCommand(strSQL, Connection); Connection.Open(); SqlDataReader Dr; Dr = Command.ExecuteReader(); if (Dr.HasRows) { if (Dr.Read()) { jsonString = Dr.GetValue(0).ToString(); } } Dr.Close(); Connection.Close(); } catch (Exception ex) { output.errorMessage = ex.Message; } finally { } JavaScriptSerializer ser = new JavaScriptSerializer(); output = ser.Deserialize<RootObjectOut>(jsonString); return output; }
private void LoadFavorites() { try { string url = string.Format("http://api.mixcloud.com/{0}/favorites/", txtUsername.Text.Trim()); WebRequest wr = WebRequest.Create(url); wr.ContentType = "application/json; charset=utf-8"; Stream stream = wr.GetResponse().GetResponseStream(); if (stream != null) { StreamReader streamReader = new StreamReader(stream); string jsonString = streamReader.ReadToEnd(); var jsonSerializer = new JavaScriptSerializer(); RootObject rootObject = jsonSerializer.Deserialize<RootObject>(jsonString); rptFavorites.DataSource = rootObject.data; rptFavorites.DataBind(); divFavorites.Visible = rootObject.data.Any(); divMessage.Visible = !divFavorites.Visible; } } catch (Exception ex) { } }
public static LocanWebFile BuildFrom(string stringRepresentation) { if (string.IsNullOrWhiteSpace(stringRepresentation)) { throw new ArgumentNullException("stringRepresentation"); } JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); return jsonSerializer.Deserialize(stringRepresentation, typeof(LocanWebFile)) as LocanWebFile; }
public static void WriteJsonResponse(HttpResponse response, object model) { var serializer = new JavaScriptSerializer(); string json = serializer.Serialize(model); response.Write(json); response.End(); }
public GlimpseResponders() { JsSerializer = new JavaScriptSerializer(); JsConverters = new List<IGlimpseConverter>(); Outputs = new List<GlimpseResponder>(); Sanitizer = new CSharpSanitizer(); }
public ActionResult DetailMovie(string movieId,string youTubeId) { if (youTubeId == "" || youTubeId == null) { youTubeId = ""; } DetailMovie movie = new Models.DetailMovie(); string responseString = ""; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:51704/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.GetAsync("api/movie?IMDBid=" + movieId + "&YouTubeid=" + youTubeId).Result; if (response.IsSuccessStatusCode) { responseString = response.Content.ReadAsStringAsync().Result; } } string jsonInput = responseString; // System.Console.Error.WriteLine(responseString); JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); movie = jsonSerializer.Deserialize<DetailMovie>(jsonInput); return View(movie); }
public static Dictionary<string, object> CreateProject(string Key, string Name) { try { string url = GetRegistryValue(Params.CEPTAH_CONN_REG_KEY, "JiraUrl"); string user = ReadDocumentProperties(Params.USER_NAME_PROP); Microsoft.Office.Core.DocumentProperty p = (Microsoft.Office.Core.DocumentProperty)Globals.ThisAddIn.Application.ActiveProject.BuiltinDocumentProperties["Manager"]; string pass = TempPass; string urlParameters = "projectname=" + HttpUtility.UrlEncode(Name.Replace(".mpp", "")) + "&projectkey=" + Key.ToUpper() + "&projectlead=" + user; //+ "&projectdesc=" + HttpUtility.UrlEncode("Описание проекта"); string FinishURL = url + "/rest/scriptrunner/latest/custom/createProject1?" + urlParameters; WebRequest request = WebRequest.Create(FinishURL); string upass = Base64Encode(user + ":" + pass); request.Headers.Add("Authorization", "Basic " + upass); request.ContentType = "application/json"; WebResponse response = request.GetResponse(); Stream s = response.GetResponseStream(); StreamReader sr = new StreamReader(s); JavaScriptSerializer ser = new JavaScriptSerializer(); return ser.Deserialize<Dictionary<string, object>>(sr.ReadToEnd()); //MessageBox.Show(json); } catch (Exception ex) { MessageBox.Show(ex.Message + " " + ex.StackTrace); return null; } }
public async Task<UserModel> Get(string Facebook_ID) { var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017"); var mongoDbServer = mongoDbClient.GetDatabase("SocialNetworks"); string facebookID = '"' + Facebook_ID + '"'; UserModel user = new UserModel(); int i = 0; var collection = mongoDbServer.GetCollection<BsonDocument>("UserInfo"); var filter = Builders<BsonDocument>.Filter.Eq("Facebook_ID", facebookID); var result = await collection.Find(filter).ToListAsync(); foreach (BsonDocument item in result) { user.Facebook_ID = item.GetElement("Facebook_ID").Value.ToString(); user.Ime = item.GetElement("Ime").Value.ToString(); user.Prezime = item.GetElement("Prezime").Value.ToString(); user.Email = item.GetElement("Email").Value.ToString(); user.DatumRodjenja = item.GetElement("DatumRodjenja").Value.ToString(); user.Hometown = item.GetElement("Hometown").Value.ToString(); user.ProfilePictureLink = item.GetElement("ProfilePictureLink").Value.ToString(); // foreach (var movie in item.GetElement("Movies").Value.AsBsonArray) // { // user.Movies[i] = movie.ToString(); // i++; // } i = 0; user._id = item.GetElement("_id").Value.ToString(); } var json = new JavaScriptSerializer().Serialize(user); return user; }
public static string GetValidate(string _ModuleName, string _A, string _B, string _C, string _D) { string Result = ""; try { System.Net.WebClient client = new System.Net.WebClient(); client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers string arr = client.DownloadString(string.Format("{0}api/Validate/{1}?&_A={2}?&_B={3}?&_C={4}?&_D={5}", System.Web.HttpContext.Current.Session["WebApiUrl"].ToString(), _ModuleName, _A, _B, _C, _D)); System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); Result = serializer.Deserialize<string>(arr); //using (var client = new HttpClient()) //{ // client.BaseAddress = new Uri(System.Web.HttpContext.Current.Session["WebApiUrl"].ToString()); // client.DefaultRequestHeaders.Accept.Clear(); // client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // var response = client.GetAsync(string.Format("api/Validate/{0}?&_A={1}?&_B={2}?&_C={3}?&_D={4}", _ModuleName, _A, _B, _C, _D)) ; //} } catch (Exception) { Result = "#Error"; } return Result; }
public ActionResult VidpubJSON(dynamic content) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new ExpandoObjectConverter() }); var json = serializer.Serialize(content); Response.ContentType = "application/json"; return Content(json); }
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { var entity = obj as User; var root = new Dictionary<string, object>(); var result = new Dictionary<string, object>(); if (entity != null) { result.Add("login", entity.Login); result.Add("firstname", entity.FirstName); result.Add("lastname", entity.LastName); result.Add("mail", entity.Email); result.Add("password", entity.Password); result.Add("must_change_passwd", entity.MustChangePassword); result.WriteIfNotDefaultOrNull(entity.AuthenticationModeId, "auth_source_id"); if (entity.CustomFields != null) { serializer.RegisterConverters(new[] { new IssueCustomFieldConverter() }); result.Add("custom_fields", entity.CustomFields.ToArray()); } root["user"] = result; return root; } return result; }
static void Main() { DateTime startDate = DateTime.Now; DateTime endDate = DateTime.Now; var context = new SupermarketChainContext(); var productData = context.SaleReports .Where(s => DateTime.Compare(s.SaleTime, startDate) > 0 && DateTime.Compare(s.SaleTime, endDate) < 0) .GroupBy(sl => sl.ProductId).Select(g => new { sum = g.Sum(p => p.Quantity), productID = g.Select(p => p.ProductId), productName = g.Select(p => p.Product.ProductName), price = g.Sum(p => p.Product.Price), vendor = g.Select(p => p.Vendor.VendorName) }); foreach (var item in productData) { decimal decNumber; double sum = Double.Parse(item.price.ToString()); double mult = sum * item.sum; JSONObject JO = new JSONObject(); JO.productID = item.productID.ElementAt(0); JO.productName = item.productName.ElementAt(0); JO.quantitySold = item.sum; JO.income = mult; JO.vendorName = item.vendor.ElementAt(0); var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(JO); File.WriteAllText(@"..\..\..\Json-Reports\" + item.productID.ElementAt(0) + ".json", json); } }