public void CamelCaseSerializationTest() { var petJson = JsonNet.Serialize(OriginalPet, PropertyNameTransforms.TitleToCamelCase); Assert.AreEqual(originalPetJson, petJson); Assert.Pass(); }
public void SerializationTest() { var petJson = JsonNet.Serialize(OriginalPet); Assert.AreEqual(petJson, OriginalPetJson); Assert.Pass(); }
async Task RunAsync(NotificationDataModel data) { var myContent = JsonNet.Serialize(data); var stringContent = new StringContent(myContent, UnicodeEncoding.UTF8, "application/json"); HttpClient client = new HttpClient(); //client.BaseAddress = new Uri("https://localhost:44333/api/SendPushNotificationPartners/"); client.BaseAddress = new Uri("https://appi-atah.azurewebsites.net/api/SendPushNotificationPartners/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); try { var responsevar = ""; HttpResponseMessage response = await client.PostAsync("https://appi-atah.azurewebsites.net/api/SendPushNotificationPartners/", stringContent); //HttpResponseMessage response = await client.PostAsync("https://localhost:44333/api/SendPushNotificationPartners/", stringContent); if (response.IsSuccessStatusCode) { responsevar = await response.Content.ReadAsStringAsync(); } Respuesta res = JsonNet.Deserialize <Respuesta>(responsevar); MessageBox.Show(res.mensaje); clean(); } catch (Exception e) { string error = e.Message; MessageBox.Show("Error con el servicio intente màs tarde"); } }
static void Main(string[] args) { string queryStr; if (args.Count() == 1) { queryStr = args[0]; } else { Console.WriteLine("Query string expected as argument"); return; } var schema = Schema.For( File.ReadAllLines("schema.graphql"), _ => { _.Types.Include <Query.Query>(); }); var execOptions = new ExecutionOptions { Schema = schema, Query = queryStr }; var docExec = new DocumentExecuter(); var task = docExec.ExecuteAsync(execOptions); task.Wait(); var result = JsonNet.Serialize(task.Result.Data); Console.WriteLine($"Request: {queryStr}"); Console.WriteLine($"Response: {result}"); }
// Финализация и закрытие программы protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); // Сохранение конфигурации File.WriteAllText(configPath, JsonNet.Serialize(config)); }
public void ConverterTest() { var petJson = JsonNet.Serialize(OriginalPet, DateConverter); var restoredPet = JsonNet.Deserialize <Pet>(petJson); Debug.Assert(restoredPet.birth.ToString() == OriginalPet.birth.ToString()); }
public string ToJson(bool indented = false) { return(JsonNet.Serialize( this, new JsonConverter <DateTime>( dt => dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss", CultureInfo.InvariantCulture), s => DateTime.ParseExact(s, "yyyy'-'MM'-'dd'T'HH':'mm':'ss", CultureInfo.InvariantCulture)))); }
public void ConverterTest() { var petJson = JsonNet.Serialize(OriginalPet, DateConverter); var restoredPet = JsonNet.Deserialize <Pet>(petJson); Assert.AreEqual(restoredPet.birth.ToString(), OriginalPet.birth.ToString()); Assert.Pass(); }
public void TestBug002() { var bug002 = new Bug002 { interval = TimeSpan.FromMinutes(2) }; var json = JsonNet.Serialize(bug002); var constructed = JsonNet.Deserialize <Bug002>(json); Assert.AreEqual(bug002.interval, constructed.interval); }
static Data() { if (!File.Exists(_settingFilePath)) { SaveFile(JsonNet.Serialize(Setting.GetDefaultSetting())); _setting = Setting.GetDefaultSetting(); } else { _setting = JsonNet.Deserialize <Setting>(GetFileData()); } }
internal void Send(Packet.PacketTypeC2S type, object payloadData) { var packetC2S = new PacketC2S(type, payloadData); _logger.LogTrace($"Sending packet: {packetC2S}"); var payload = Encoding.Unicode.GetBytes(JsonNet.Serialize(packetC2S)); using (var memStream = new MemoryStream()) { var writer = new BinaryWriter(memStream); writer.Write(payload.Length); writer.Write(payload); _easySocket.SendAsync(memStream.ToArray()); } }
public void WritetoFile(MediaList mediaList, Movie movie) { JSONFile jsonfile = new JSONFile("media.json"); using (StreamWriter outputFile = new StreamWriter(jsonfile.Path)) { foreach (Media media in mediaList.mediaList) { var temp = JsonNet.Serialize(media); outputFile.WriteLine(temp); } outputFile.Close(); } }
public void Save() { lock (lock_object) { _fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _fileName); var requestStringfy = JsonNet.Serialize(_requests, new GuidConverter()); if (string.IsNullOrWhiteSpace(requestStringfy)) { return; } using (var stream = new StreamWriter(_fileName, false, Encoding.UTF8)) { stream.Write(requestStringfy); } } }
/// <summary> /// Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. Any previous /// time to live associated with the key is discarded on successful SET operation. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expiry"></param> /// <returns></returns> public bool Set(string key, object value, TimeSpan?expiry = null) { Check.NotEmpty(key, nameof(key)); Check.NotNull(value, nameof(value)); try { var db = GetDatabase(); return(db.StringSet(key, JsonNet.Serialize(value), expiry)); } catch (Exception ex) { // Don't let cache server unavailability bring down the application. _logger.Error(ex, $"Unhandled exception trying to SET '{key}'"); } return(false); }
public async Task <IActionResult> Stripe([FromBody] StripeEvent stripeEvent) { var result = new StripeBaseCommand(); try { switch (stripeEvent.Type) { case StripeEvents.ChargeRefunded: StripeRefundModel refund = StripeEventUtility.ParseEventDataItem <StripeRefundModel>(stripeEvent.Data.Object); await _stripeSvc.RefundPayment(refund.id, refund.metadata.AccountNumber, refund.amount_refunded); break; case StripeEvents.CustomerSubscriptionUpdated: break; case StripeEvents.InvoicePaymentFailed: // Invoice is sent and payment results in failure. //Undo Payment break; } } catch (StripeException ex) { var message = $"Unhandled {nameof(StripeException)} caught in {nameof(WebhookController)}.{nameof(Stripe)}. StripeEvent.Type: {stripeEvent.Type}"; _logger.Error(ex, message); result.Logs.Add(message); //await SendWebHookErrorEmail($"[Stripe Webhook Stripe Exception ({_env.EnvironmentName})]", stripeEvent, ex); } catch (Exception ex) { var message = $"Unhandled Exception caught in {nameof(WebhookController)}.{nameof(Stripe)}. StripeEvent.Type: {stripeEvent.Type}"; _logger.Error(ex, message); result.Logs.Add(message); //await SendWebHookErrorEmail($"[Stripe Webhook System Exception ({_env.EnvironmentName})]", stripeEvent, ex); } return(Ok(JsonNet.Serialize(new { result.Logs }, prettyPrint: true))); }
static void Main(string[] args) { var json = File.ReadAllText("user.json"); Console.WriteLine(json); User usuario = new User() { Name = "du", Age = 20, Email = "*****@*****.**" }; json = JsonNet.Serialize(usuario); usuario = JsonNet.Deserialize <User>(json); // Console.WriteLine(usuario.Name); // Console.WriteLine(usuario.Age); // Console.WriteLine(usuario.Email); File.WriteAllText("user.json", json); }
static void Main(string[] args) { BaseDAL <User> dal = new BaseDAL <User>(); User user = new User(); user.Id = Guid.NewGuid().ToString().Replace("-", ""); dal.Add(user); dal.SaveChanges(); List <User> list = dal.QueryWhere(s => true); //json转化 var userJson = JsonNet.Serialize(list, JsonHelper.dateConverter); //var userList = JsonNet.Deserialize<List<User>>(userJson, JsonHelper.dateConverter); Console.WriteLine(userJson); Console.Read(); }
public static void SaveToFile(CharlieModel model) { var pref = new Preferences { WindowX = model.WindowX, WindowY = model.WindowY, WindowHeight = model.WindowHeight, WindowWidth = model.WindowWidth, PreviousLoadedSims = model.PreviousLoaded.Get(), SimDelay = model.SimDelay, LogEveryIteration = model.LogEveryIteration, RenderHeight = model.RenderHeight, RenderWidth = model.RenderWidth }; if (!Directory.Exists(PrefenceDir)) { Directory.CreateDirectory(PrefenceDir); } File.WriteAllText(PreferenceFile, JsonNet.Serialize(pref)); }
// Issue 9 public void JsonNetIgnoreAttributeTest() { var test_object = new TestClass005 { Id = 81, Name = "Tester 005", SecurityKey = "Top Secret", NickName = "Superman" }; var json_text = JsonNet.Serialize(test_object); Assert.AreEqual(json_text, "{\"Id\":81,\"Name\":\"Tester 005\",\"NickName\":\"Superman\"}"); json_text = "{\"Id\":81,\"Name\":\"Tester 005\",\"SecurityKey\":\"Top Secret\",\"NickName\":\"Superman\"}"; var test_object2 = JsonNet.Deserialize <TestClass005>(json_text); Assert.AreEqual(test_object.Id, test_object2.Id); Assert.AreEqual(test_object.Name, test_object2.Name); Assert.AreNotEqual(test_object.SecurityKey, test_object2.SecurityKey); Assert.AreEqual(test_object.NickName, test_object2.NickName); }
static void Main(string[] args) { DBEntities db = new DBEntities(); //新增 User user = new User(); user.Id = Guid.NewGuid().ToString().Replace("-", ""); db.User.Add(user); db.SaveChanges(); //查询 List <User> list = db.User.ToList(); //json转化 var userJson = JsonNet.Serialize(list, JsonHelper.dateConverter); //var userList = JsonNet.Deserialize<List<User>>(userJson, JsonHelper.dateConverter); Console.WriteLine(userJson); Console.Read(); }
static void Main(string[] args) { Enemy enemy = new Enemy() { Weapon = 50 }; GoldBox goldBox = new GoldBox(); GoldKey goldKey = new GoldKey(); SilverKey silverKey = new SilverKey(); BronzKey bronzKey = new BronzKey(); Cell cell1 = new Cell(enemy); Cell cell2 = new Cell(goldKey); Cell cell3 = new Cell(goldBox); Cell cell4 = new Cell(); Cell[,] cells = new Cell[, ] { { cell4, cell1, cell3 }, { cell2, cell4, cell2 }, }; Player player = new Player(); player.Keys.Add(silverKey); player.Keys.Add(goldKey); player.Keys.Add(bronzKey); Board board = new Board(cells); board.Player = player; GameDirector gameDirector = new GameDirector(board); Console.WriteLine("hhhhhhhhhhh"); JsonSerializer serializer = new JsonSerializer(); var petJson = JsonNet.Serialize(gameDirector); Console.WriteLine(petJson); File.WriteAllText(@"P:\Intro Work Shop\Sample Game\PCMan\PCMan\json.json", petJson); var jsonString = File.ReadAllText(@"P:\Intro Work Shop\Sample Game\PCMan\PCMan\json.json"); Console.WriteLine($"Read From File:\n{jsonString}"); var pet = JsonNet.Deserialize <GameDirector>(jsonString); Console.WriteLine($"after Deserialization:\n{pet}"); //JsonSerializer.Deserialize<GameDirector>(jsonString); //IOcupant ocupant = new Enemy() { Weapon = 100 }; //Cell[,] cells = new Cell[,] { // { new Cell(ocupant), new Cell(ocupant), new Cell(ocupant) }, // { new Cell(ocupant), new Cell(ocupant), new Cell(ocupant) } //}; //Board board = new Board(cells); //foreach (var item in cells) //{ // if (item._ocupant is Enemy e) // { // Console.WriteLine($"----{ e.Weapon.ToString()}"); // } //} Console.WriteLine("Hello World!"); }
private static Status universalObjeccctRetriver(string query, SqlCommand cmd, int type) { SqlConnection con = new SqlConnection(ConnectionInit.ConnectionString); Status status = new Status(); status.Json_data = "{"; try { con.Open(); cmd.Connection = con; cmd.CommandText = query; SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { if (reader.HasRows) { if (reader.Read()) { if (type == CHECK_IF_EXISTS_REQUESTS) { int Chat_id = reader.GetInt32(0); status.Json_data += "\"Chat_id\":" + "\"" + JsonNet.Serialize(Chat_id) + "\","; } else if (type == SENDDING_MESSAGE) { int Message_id = int.Parse(reader.GetSqlValue(0).ToString()); status.Json_data += "\"Message_id\":" + "\"" + JsonNet.Serialize(Message_id) + "\""; } } if (reader.NextResult()) { if (reader.Read()) { if (type == CHECK_IF_EXISTS_REQUESTS) { int Message_id = int.Parse(reader.GetSqlValue(0).ToString()); status.Json_data += "\"Message_id\":" + "\"" + JsonNet.Serialize(Message_id) + "\""; } } } } status.Json_data += "}"; status.State = 1; status.Exception = "Done"; } else { status.State = 0; status.Exception = "not found"; status.Json_data = ""; } reader.Close(); } catch (Exception e1) { status.State = -1; status.Exception = e1.Message; } finally { con.Close(); } return(status); }
public static void Save() { string json = JsonNet.Serialize(conf); File.WriteAllText(DEFAULT_CONF_FILE, json); }
private ResultColumnEntry TestSerializer <T>(dynamic ser, int numOfObjects, out int sizeInBytes, out bool success, out string regeneratedObjAsJson) { var sw = new Stopwatch(); // BINARY serializers // eg: ProtoBufs, Bin Formatter etc if (ser.IsBinary()) { byte[] binOutput; sw.Reset(); sw.Start(); for (int i = 0; i < numOfObjects; i++) { binOutput = ser.Serialize(_originalObject); _testObject = ser.Deserialize(binOutput); } sw.Stop(); // Find size outside loop to avoid timing hits binOutput = ser.Serialize(_originalObject); sizeInBytes = binOutput.Count(); } // TEXT serializers // eg. JSON, XML etc else { sw.Reset(); sw.Start(); for (int i = 0; i < numOfObjects; i++) { string strOutput = ser.Serialize(_originalObject); _testObject = ser.Deserialize(strOutput); } sw.Stop(); // Find size outside loop to avoid timing hits // Size as bytes for UTF-8 as it's most common on internet var encoding = new System.Text.UTF8Encoding(); byte[] strInBytes = encoding.GetBytes(ser.Serialize(_originalObject)); sizeInBytes = strInBytes.Count(); } var entry = new ResultColumnEntry(); entry.Iteration = numOfObjects; long avgTicks = sw.Elapsed.Ticks / numOfObjects; if (avgTicks == 0) { // sometime when running windows inside a VM this is 0! Possible vm issue? //Debugger.Break(); } entry.Time = new TimeSpan(avgTicks); // Debug: To aid printing to screen, human debugging etc. Json used as best for console presentation var jsonSer = new JsonNet <T>(); string orignalObjectAsJson = JsonHelper.FormatJson(jsonSer.Serialize(_originalObject)); regeneratedObjAsJson = JsonHelper.FormatJson(jsonSer.Serialize(_testObject)); success = true; if (orignalObjectAsJson != regeneratedObjAsJson) { Console.WriteLine(">>>> {0} FAILED <<<<", ser.GetName()); Console.WriteLine("\tOriginal and regenerated objects differ !!"); Console.WriteLine("\tRegenerated objects is:"); Console.WriteLine(regeneratedObjAsJson); success = false; } return(entry); }
private void MenuItem_Save(object sender, RoutedEventArgs e) { handleDialog(new System.Windows.Forms.SaveFileDialog(), path => File.WriteAllText(path, JsonNet.Serialize(getUserInput()))); }
private void Button1_Click(object sender, EventArgs e) { if (nome.Text == "") { MessageBox.Show("O campo 'Descrição' é obrigatório e não pode ficar vazio.", "Alerta do sistema", MessageBoxButtons.OK); } else { Cliente cliente = new Cliente(); cliente.nome = nome.Text; cliente.cpf = cpf.Text; cliente.rg = rg.Text; cliente.nascimento = nascimento.Value.Date; nascimento.CustomFormat = "dd/MM/yyyy"; Console.WriteLine(nascimento.Value); //int selectedIndex = plano.SelectedIndex; int selectedValue = (int)plano.SelectedValue; cliente.plano = selectedValue; cliente.valor = preco.Text; Console.WriteLine(selectedValue); string DATA = JsonNet.Serialize(cliente); string URL = "http://localhost:21529/PointBarber/clientes"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "POST"; request.ContentType = "application/json"; request.Accept = "application/json"; request.ContentLength = DATA.Length; try { using (Stream webStream = request.GetRequestStream()) using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII)) { requestWriter.Write(DATA); } WebResponse webResponse = request.GetResponse(); HttpStatusCode response_code = ((HttpWebResponse)webResponse).StatusCode; if (response_code == HttpStatusCode.Created) { nome.Text = preco.Text = ""; if (MessageBox.Show("Registro salvo com sucesso!" + Environment.NewLine + "Gostaria de cadastrar outra barbearia?", "Alerta do sistema", MessageBoxButtons.YesNo) == DialogResult.Yes) { TelaCadastro telaCadastrar = new TelaCadastro(); telaCadastrar.MdiParent = this; telaCadastrar.Show(); } } else { Stream webStream = webResponse.GetResponseStream(); StreamReader responseReader = new StreamReader(webStream); string response = responseReader.ReadToEnd(); MessageBox.Show("Erro no servidor:", "Alerta do sistema", MessageBoxButtons.OK); } } catch (Exception ex) { MessageBox.Show("Erro no lado do servidor.", "Alerta do sistema", MessageBoxButtons.OK); } } }
public static void SaveSetting(Setting st) { _setting = st; SaveFile(JsonNet.Serialize(st)); }