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 static dynamic DeserializeJson(string jsonString) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new ExpandoObjectConverter() }); return serializer.Deserialize<ExpandoObject>(jsonString); }
public override object InvokeMember(Func<object> proceed, object self, string name, INamedEnumerable<object> args) { // Call to Json function // Stuff.Json() -> serialize to string // Stuff.Json(string foo) -> meld from Json string if (name == "Json") { if (args.Positional.Count() == 0) { // Serialize var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new ClayJavaScriptConverter() }); dynamic dself = self; return serializer.Serialize(dself.Get()); } else { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new ClayJavaScriptConverter() }); dynamic stuff = self; // TODO: Accept some named parameters? foreach (var p in args.Positional) { // Deserialize and meld each Json string // TODO: Throw parameter error if p is not a string stuff.Meld(serializer.Deserialize((String)p, typeof(Stuff))); } return self; } } return proceed(); }
public string Serialize(object value) { JavaScriptSerializer ser = new JavaScriptSerializer(); List<JavaScriptConverter> converters = new List<JavaScriptConverter>(); if (value != null) { Type type = value.GetType(); if (type == typeof(DataTable) || type == typeof(DataRow) || type == typeof(DataSet)) { converters.Add(new WebExtensionsDataRowConverter()); converters.Add( new WebExtensionsDataTableConverter()); converters.Add(new WebExtensionsDataSetConverter()); } if (value is IDataReader ) { converters.Add(new DataReaderConverter()); } if (converters.Count > 0) ser.RegisterConverters(converters); } return ser.Serialize(value); }
/// <summary> /// When called by the action invoker, writes the JSON formatted result to the response. /// </summary> /// <param name="context">The context that the result is executed in.</param> public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."); 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) { JavaScriptSerializer serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new Lib.Web.Mvc.JQuery.JqGrid.Serialization.JqGridScriptConverter() }); response.Write(serializer.Serialize(Data)); } }
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { ExpandoObject expando = (ExpandoObject)obj; if (expando != null) { // Create the representation. Dictionary<string, object> result = new Dictionary<string, object>(); foreach (KeyValuePair<string, object> item in expando) { var value = item.Value ?? ""; if (value is DateTime) result.Add(item.Key, ((DateTime)value).ToShortDateString()); else if (value is ExpandoObject) { var ser = new JavaScriptSerializer(); ser.RegisterConverters(new []{new ExpandoObjectConverter()}); var res = ser.Serialize(value); result.Add(item.Key, res); } else { var collection = value as ICollection; if (collection != null) { var ser = new JavaScriptSerializer(); var res = ser.Serialize(collection); result.Add(item.Key, res); } else result.Add(item.Key, value.ToString()); } } return result; } return new Dictionary<string, object>(); }
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (controllerContext == null) throw new ArgumentNullException("controllerContext"); if (bindingContext == null) throw new ArgumentNullException("bindingContext"); JavaScriptSerializer serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new Lib.Web.Mvc.JQuery.JqGrid.Serialization.JqGridScriptConverter() }); string jsonString = String.Empty; if (controllerContext.RequestContext.HttpContext.Request.ContentType.Contains("application/json")) { controllerContext.HttpContext.Request.InputStream.Seek(0, SeekOrigin.Begin); using (StreamReader jsonReader = new StreamReader(controllerContext.HttpContext.Request.InputStream)) jsonString = jsonReader.ReadToEnd(); } else jsonString = controllerContext.HttpContext.Request[bindingContext.ModelName]; if (String.IsNullOrEmpty(jsonString)) return null; else return serializer.Deserialize(jsonString, bindingContext.ModelType); }
public static Weather ObterInformacoes() { WebRequest request = WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?id=3448439&lang=pt&units=metric"); var clima = new Weather(); using (Stream s = request.GetResponse().GetResponseStream()) { using (var sr = new StreamReader(s)) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); dynamic obj = serializer.Deserialize(sr.ReadToEnd(), typeof(object)); dynamic weather = obj.weather[0]; clima.Clima = weather.description; clima.Icone = weather.icon; dynamic main = obj.main; clima.Temperatura = main.temp; clima.TemperaturaMinima = main.temp_min; clima.TemperaturaMaxima = main.temp_max; } } return clima; }
public static string ToJsonString(dynamic content) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] {new ExpandoObjectConverter()}); var json = serializer.Serialize(content); return json; }
public static dynamic GetJson(this string jsontext) { JavaScriptSerializer jss = new JavaScriptSerializer(); jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); return jss.Deserialize(jsontext, typeof(object)) as dynamic; }
public void TestJson() { var js = new JavaScriptSerializer(); js.RegisterConverters(new JavaScriptConverter[] { JsonConverter.createConverter<TestA>() }); var data = js.Serialize(new TestA { A = "xxx" }); Console.WriteLine(data); }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; if (!string.IsNullOrEmpty(this.ContentType)) { response.ContentType = this.ContentType; } else { response.ContentType = "application/json"; } if (this.ContentEncoding != null) { response.ContentEncoding = this.ContentEncoding; } if (this.Data != null) { JavaScriptSerializer serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new ArabiaJavaScriptConverter() }); response.Write(serializer.Serialize(this.Data)); } }
private static void ApplyConverters(Type type, JavaScriptSerializer serializer) { if (type.GetInterface(typeof(IAsyncUploadConfiguration).FullName) != null) { serializer.RegisterConverters(new AsyncUploadConfigurationConverter[] { new AsyncUploadConfigurationConverter() }); } }
public static dynamic Decode(string json) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); dynamic obj = serializer.Deserialize(json, typeof(object)); return obj; }
public static dynamic GetJsonResponse(string url) { var jss = new JavaScriptSerializer(); jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); var json = GetStringResponse(url); return jss.Deserialize(json, typeof(object)) as dynamic; }
protected Stream Serialize(object obj) { var js = new JavaScriptSerializer(); js.RegisterConverters(new List<JavaScriptConverter>() { new ExpandoObjectSerializer() }); var mem = new MemoryStream(Encoding.UTF8.GetBytes(js.Serialize(obj))); WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8"; return mem; }
/// <summary> /// Parses this string and returns equivalent dynamic object, always check for null values :) /// </summary> /// <param name="phrase"></param> /// <returns></returns> public static dynamic ParseJSON(this string phrase) { JavaScriptSerializer jss = new JavaScriptSerializer(); jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); dynamic obj = jss.Deserialize(phrase, typeof(object)); return obj; }
public static dynamic Get(Uri url) { try { // Query API String oResponse = null; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { oResponse = (new StreamReader(response.GetResponseStream())).ReadToEnd(); } // Deserialize Data var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); return serializer.Deserialize(oResponse, typeof(object)); } catch (WebException e) { if (e is WebException && ((WebException)e).Status == WebExceptionStatus.ProtocolError) { using (HttpWebResponse response = (HttpWebResponse)e.Response) { String oResponse = (new StreamReader(response.GetResponseStream())).ReadToEnd(); MessageBox.Show(oResponse); } } } return null; }
public string ToJson(object data) { var javaScriptSerializer = new JavaScriptSerializer(); javaScriptSerializer.RegisterConverters(new[] {new DynamicHashConverter()}); var serialize = javaScriptSerializer.Serialize(data); return serialize; }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("Acesso negado"); } 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 serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new EntidadeJavaScriptConverter() }); response.Write(serializer.Serialize(Data)); } }
public static string ToJSON(this object obj, int recursionDepth) { JavaScriptSerializer serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new NullPropertiesConverter() }); serializer.RecursionLimit = recursionDepth; return serializer.Serialize(obj); }
/// <summary> /// Fetch Json Array (Json within ['d']['results']) from response /// </summary> public static string GetJsonArray(string response) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new JavaScriptConverter[] { new JssDateTimeConverter() }); try { ArrayList results; var dict = (Dictionary<string, object>)serializer.Deserialize<object>(response); var innerPart = dict["d"]; if (innerPart.GetType() == typeof(Dictionary<string, object>)) { var d = (Dictionary<string, object>)dict["d"]; results = (ArrayList)d["results"]; } else { results = (ArrayList)innerPart; } return GetJsonFromResultDictionary(results); } catch (Exception e) { throw new IncorrectJsonException(e.Message); } }
/// <summary> /// A helper method that generates a JSON string /// </summary> /// <param name="sb">The string builder.</param> private void ToString(ref StringBuilder sb) { sb.Append("{"); var needComma = false; foreach (var pair in mDictionary) { if (needComma) { sb.Append(","); } needComma = true; var value = pair.Value; var name = pair.Key; if (value == null) { sb.AppendFormat("\"{0}\":\"{1}\"", name, ""); } else { sb.AppendFormat("\"{0}\":", name); JavaScriptSerializer serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonObjectConverter() }); serializer.Serialize(value, sb); } } sb.Append("}"); }
public Boolean Authenticate(String email, String Password) { try { Login login = this.serverws.GetRpcProxy<Login>(); var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); dynamic json = login.Login(email, Password); dynamic res = serializer.Deserialize(json.ToString(), typeof(object)); if (res.token == null) { return false; } else { this.ServeurAuthToken = res.token; this.ServeurIsAuthentified = true; return true; } } catch (Exception e) { Console.WriteLine(e.Message); return false; } }
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { var entity = obj as TimeEntry; var root = new Dictionary<string, object>(); var result = new Dictionary<string, object>(); if (entity != null) { result.WriteIdIfNotNull(entity.Issue, "issue_id"); result.WriteIdIfNotNull(entity.Project, "project_id"); result.WriteIdIfNotNull(entity.Activity, "activity_id"); if (!entity.SpentOn.HasValue) entity.SpentOn = DateTime.Now; result.Add("spent_on", entity.SpentOn.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); result.Add("hours", entity.Hours); result.Add("comments", entity.Comments); if (entity.CustomFields != null) { serializer.RegisterConverters(new[] { new IssueCustomFieldConverter() }); result.Add("custom_fields", entity.CustomFields.ToArray()); } root["time_entry"] = result; return root; } return result; }
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; }
private static dynamic ParseResponseData(string response) { var jss = new JavaScriptSerializer(); jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); var data = jss.Deserialize(response, typeof(object)) as dynamic; return data; }
public static dynamic JsonToDynamic(string response) { var jss = new JavaScriptSerializer(); jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() }); var dynamicResponse = jss.Deserialize(response, typeof(object)) as dynamic; return dynamicResponse; }
public void When_Pools_Element_Is_Empty_BootstrapConfigurationException_Is_Thrown() { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new List<JavaScriptConverter>{ClusterNode.BootstrapConfigConverterInstance}); var config = File.ReadAllText(@"Data\\bootstrap-with-empty-pools.json"); var info = serializer.Deserialize<BootstrapInfo>(config); }
public async Task Connect() { await _client.ConnectAsync(IPAddress.Parse(Ip).MapToIPv4(), 9073); _stream = _client.GetStream(); _streamReader = new StreamReader(_stream); _serializer = new JavaScriptSerializer(); _serializer.RegisterConverters(new List<JavaScriptConverter>() { new JSTuple2Converter<int, int?>() }); }