本文整理汇总了C#中System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject方法的典型用法代码示例。如果您正苦于以下问题:C# Script.Serialization.JavaScriptSerializer.DeserializeObject方法的具体用法?C# Script.Serialization.JavaScriptSerializer.DeserializeObject怎么用?C# Script.Serialization.JavaScriptSerializer.DeserializeObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Web.Script.Serialization.JavaScriptSerializer
的用法示例。
在下文中一共展示了Script.Serialization.JavaScriptSerializer.DeserializeObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
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();
}
}
示例2: ParentsSectionChat_Click
protected void ParentsSectionChat_Click(object sender, EventArgs e)
{
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
var tempMessageCount = 0;
var actualMessageCount = 0;
//Put ur db logic to get channel name'
//foreach (var item in collection)
//{
var channel = "fcf173dc-5d2c-4e1a-80a5-b92068d91019";
tempMessageCount = 0;
actualMessageCount = 0; //Your total message count
string content = GetHistoryContent(channel);
if (content.Length > 47)
{
var messageList = json_serializer.DeserializeObject(content.Substring(1, content.Length - 38));
tempMessageCount = ((object[])messageList).Count();
actualMessageCount = tempMessageCount;
while (tempMessageCount == 100)
{
var startCounter = content.Substring(content.Length - 36, 17);
var morecontent = GetHistoryContent(channel, startCounter);
if (content.Length > 47)
{
var moreMessageList = json_serializer.DeserializeObject(content.Substring(1, content.Length - 38));
tempMessageCount = ((object[])moreMessageList).Count();
actualMessageCount = actualMessageCount + tempMessageCount;
}
}
}
//}
}
示例3: TestMethod1
public void TestMethod1()
{
string jsonstr = "{x:11,y:'abcd'}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
object obj = serializer.DeserializeObject(jsonstr);
Dictionary<string, object> dic = serializer.DeserializeObject(jsonstr) as Dictionary<string, object>;
dd d = serializer.Deserialize<dd>(jsonstr);
}
示例4: SerializeData
void SerializeData()
{
for (Int32 i = 0; i < _content.Count; i++)
{
String line = GetFixedLine(i);
Match match = Defines.GetDataRegex(_typeId, _subTypeId).Match(line);
if (match.Success)
{
JavaScriptSerializer json = new JavaScriptSerializer()
{
MaxJsonLength = int.MaxValue
};
if (line.Contains("_totalCount"))
TotalCount = UInt32.Parse(Defines.GetStringBetweenTwoOthers(line, "_totalCount: ", ","));
else
TotalCount = 0;
Objects = (Object[])json.DeserializeObject(match.Groups[1].Captures[0].Value);
}
}
if (Objects == null)
Objects = new Object[0];
}
示例5: GeocodeGoogle
public static List<string> GeocodeGoogle(string postcode)
{
var longlat = new List<string>();
var req = (HttpWebRequest)WebRequest.Create(string.Format("http://www.google.com/uds/GlocalSearch?q={0}&v=1.0", postcode));
using (var resp = req.GetResponse())
using (var respStream = resp.GetResponseStream())
using (var reader = new StreamReader(respStream, System.Text.Encoding.UTF8, true))
{
var response = reader.ReadToEnd();
var serializer = new JavaScriptSerializer();
var deserialized = (Dictionary<string, object>)serializer.DeserializeObject(response);
var responseData = (Dictionary<string, object>)deserialized["responseData"];
var results = (object[])responseData["results"];
try
{
var resultsData = (Dictionary<string, object>)results[0];
longlat.Add(resultsData["lat"].ToString());
longlat.Add(resultsData["lng"].ToString());
longlat.Add(resultsData["title"].ToString());
}
catch (Exception)
{
longlat.Add("0");
longlat.Add("0");
longlat.Add("No Result");
}
return longlat;
}
}
示例6: GetSetInfo
public async Task<string> GetSetInfo(string sourceId, string set)
{
JavaScriptSerializer jser = new JavaScriptSerializer();
dynamic sobj = jser.DeserializeObject(set) as dynamic;
EntitySetType type;
if (Enum.TryParse<EntitySetType>(sobj["set"], out type))
{
string filter = null;
if (sobj.ContainsKey("setFilter"))
filter = sobj["setFilter"];
switch (type)
{
case EntitySetType.User:
{
UserServiceProxy svc = new UserServiceProxy();
var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter);
JavaScriptSerializer ser = new JavaScriptSerializer();
string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters });
return json;
}
case EntitySetType.Role:
{
RoleServiceProxy svc = new RoleServiceProxy();
var si = await svc.GetSetInfoAsync(ApplicationContext.ClientContext, filter);
JavaScriptSerializer ser = new JavaScriptSerializer();
string json = ser.Serialize(new { EntityCount = si.EntityCount, Sorters = si.Sorters });
return json;
}
}
}
return null;
}
示例7: ShouldAddGrants
public void ShouldAddGrants()
{
var token = new AccessToken("AC456", "SK123", "foobar");
var delta = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var timestamp = (int)Math.Floor(delta.TotalSeconds);
token.AddGrant(new ConversationsGrant());
token.AddGrant(new IpMessagingGrant());
var encoded = token.ToJWT();
Assert.IsNotNull(encoded);
Assert.IsNotEmpty(encoded);
var decoded = JsonWebToken.Decode(encoded, "foobar");
Assert.IsNotEmpty(decoded);
var serializer = new JavaScriptSerializer();
var payload = (Dictionary<string, object>)serializer.DeserializeObject(decoded);
Assert.IsNotNull(payload);
Assert.AreEqual("SK123", payload["iss"]);
Assert.AreEqual("AC456", payload["sub"]);
var exp = Convert.ToInt64(payload["exp"]);
Assert.AreEqual(timestamp + 3600, exp);
var jti = (string)payload["jti"];
Assert.AreEqual("SK123-" + timestamp.ToString(), jti);
var grants = (Dictionary<string, object>)payload["grants"];
Assert.AreEqual(2, grants.Count);
Assert.IsNotNull(grants["rtc"]);
Assert.IsNotNull(grants["ip_messaging"]);
}
示例8: BookmarkDonor
public ActionResult BookmarkDonor(int accountId)
{
if (!Request.IsAuthenticated)
{
return RedirectToAction("LogOn", "Account");
}
else
{
Models.BookmarkedDonor book = new MPXMobile.Models.BookmarkedDonor();
book.Donor_ID = accountId;
book.User_ID = HttpContext.User.Identity.Name;
var status = Models.Donors.BookmarkDonor(book);
ViewData["BookmarkedDonors"] = status;
if (IsAjaxRequest())
{
string message = string.Empty;
JavaScriptSerializer serializer = new JavaScriptSerializer();
object jsonData = serializer.DeserializeObject(status.ToString());
return Json(new { jsonData });
}
else
{
return RedirectToAction("BookmarkedDonors", "Home");
}
}
}
示例9: ShouldHaveNbf
public void ShouldHaveNbf()
{
var token = new AccessToken("AC456", "SK123", "foobar");
var now = DateTime.UtcNow;
token.Nbf = AccessToken.ConvertToUnixTimestamp(now);
var delta = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var timestamp = (int)Math.Floor(delta.TotalSeconds);
var encoded = token.ToJWT();
Assert.IsNotNull(encoded);
Assert.IsNotEmpty(encoded);
var decoded = JsonWebToken.Decode(encoded, "foobar");
Assert.IsNotEmpty(decoded);
var serializer = new JavaScriptSerializer();
var payload = (Dictionary<string, object>)serializer.DeserializeObject(decoded);
Assert.IsNotNull(payload);
Assert.AreEqual("SK123", payload["iss"]);
Assert.AreEqual("AC456", payload["sub"]);
Assert.AreEqual(AccessToken.ConvertToUnixTimestamp(now), payload["nbf"]);
var exp = Convert.ToInt64(payload["exp"]);
Assert.AreEqual(timestamp + 3600, exp);
var jti = (string)payload["jti"];
Assert.AreEqual("SK123-" + timestamp.ToString(), jti);
var grants = (Dictionary<string, object>)payload["grants"];
Assert.AreEqual(0, grants.Count);
}
示例10: toJSON
private String toJSON(string[] response) {
JavaScriptSerializer serializer = new JavaScriptSerializer();
foreach (var str in response) {
if (String.IsNullOrEmpty(str))
continue;
var json = serializer.DeserializeObject(str);
if (!(json is IDictionary<string, object>))
continue;
IDictionary<string, object> dict = (IDictionary<string, object>)json;
var results = (object[])dict["result"];
if (results == null || results.Length == 0)
continue;
var result = (IDictionary<string, object>)results[0];
var alts = (object[])result["alternative"];
if (alts == null || alts.Length == 0)
continue;
var alt = (IDictionary<string, object>)alts[0];
WSRConfig.GetInstance().logDebug("[Google Recognize]", "toJSON: " + alt["confidence"] + " : " + alt["transcript"]);
return (string)alt["transcript"];
}
return "";
}
示例11: DeserializeJSONCollectionFile
public static object DeserializeJSONCollectionFile(string filePath)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
Assembly assembly = Assembly.GetExecutingAssembly();
string collectionToCreate = string.Empty;
using (StreamReader sr = new StreamReader(assembly.GetManifestResourceStream(filePath)))
{
collectionToCreate = sr.ReadToEnd();
}
Dictionary<string, object> collectionDictionary = javaScriptSerializer.DeserializeObject(collectionToCreate) as Dictionary<string, object>;
string collectionTypeString = collectionDictionary.Keys.First();
Type collectionType = Type.GetType(collectionTypeString);
object result = Activator.CreateInstance(collectionType);
object[] objectArray = collectionDictionary.First().Value as object[];
foreach (object o in objectArray)
{
Dictionary<string, object> objectDictionary = (Dictionary<string, object>)o;
string objectTypeString = objectDictionary.Keys.First();
Type objectType = Type.GetType(objectTypeString);
object objectToAdd = Activator.CreateInstance(objectType);
Dictionary<string, object> properties = objectDictionary.First().Value as Dictionary<string, object>;
YellowstonePathology.Business.Persistence.JSONReaderPropertyWriter jsonReaderPropertyWriter = new Persistence.JSONReaderPropertyWriter(objectToAdd, properties);
jsonReaderPropertyWriter.WriteProperties();
result.GetType().GetMethod("Add").Invoke(result, new Object[] { objectToAdd });
}
return result;
}
示例12: UpdateReadings
private void UpdateReadings()
{
// Create a request for the URL.
WebRequest request = WebRequest.Create("http://api.thingspeak.com/channels/26429/feed/last.json");
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
JavaScriptSerializer deserializer = new JavaScriptSerializer();
Dictionary<string, object> data = (Dictionary<string, object>)deserializer.DeserializeObject(responseFromServer);
lblStoveTemp.Text = (String)data["field1"];
lblAmbientTemp.Text = (String)data["field2"];
lblDamper.Text = (String)data["field3"];
DateTime toDateTime = DateTime.Parse((String)data["created_at"]);
lblTime.Text = toDateTime.AddHours(1).ToShortTimeString();
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
示例13: Get_Launch_Specific_Data
public static bool Get_Launch_Specific_Data()
{
try
{
if (Utils.is_amazon_machine)
{
string sURL = "http://169.254.169.254/latest/user-data/";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
WebProxy myProxy = new WebProxy("myproxy", 80);
myProxy.BypassProxyOnLocal = true;
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(objStream);
user_Data_String = sr.ReadToEnd();
}
Console.WriteLine("user_Data_String="+user_Data_String);
JavaScriptSerializer serializer = new JavaScriptSerializer();
CFG = serializer.DeserializeObject(user_Data_String) as Dictionary<string, object>;
}
catch (Exception e)
{
Console.WriteLine("Excpetion in Get_Launch_Specific_Data(). = " + e.Message);
return false;
}
return true;
}
示例14: AutomationConnection
// cloud only
public AutomationConnection(Connection cloudConnection, ConnectionType cloudConnectionType)
: base(cloudConnection.Name, null, cloudConnection.Properties.LastModifiedTime.LocalDateTime)
{
this.ConnectionType = cloudConnectionType.Name;
JavaScriptSerializer jss = new JavaScriptSerializer();
this.ValueFields = new Dictionary<string, Object>();
foreach(KeyValuePair<string, string> field in cloudConnection.Properties.FieldDefinitionValues)
{
if(cloudConnectionType.Properties.FieldDefinitions[field.Key].Type.Equals(AutomationISE.Model.Constants.ConnectionTypeFieldType.String))
{
this.ValueFields.Add(field.Key, field.Value);
}
else
{
try
{
var value = jss.DeserializeObject(field.Value.ToLower());
this.ValueFields.Add(field.Key, value);
}
catch
{
this.ValueFields.Add(field.Key, field.Value);
}
}
}
}
示例15: OnActionExecuting
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//
// Get a shortcut to context objects
//
var request = filterContext.HttpContext.Request;
var server = filterContext.HttpContext.Server;
string contentType = request.ContentType;
if (string.IsNullOrEmpty(contentType)) return;
if (!contentType.Contains("application/json")) return;
string paramValue = request.QueryString.ToString();
if (request.RequestType == "GET")
paramValue = server.UrlDecode(paramValue);
else
using (var reader = new StreamReader(request.InputStream))
paramValue = reader.ReadToEnd();
var serializer = new JavaScriptSerializer();
var rawResult = (IDictionary<string, object>)serializer.DeserializeObject(paramValue);
foreach (var item in filterContext.ActionDescriptor.GetParameters())
{
var deserializeMethod = serializer.GetType()
.GetMethods().First(m => m.Name == "ConvertToType")
.MakeGenericMethod(item.ParameterType);
filterContext.ActionParameters[item.ParameterName] = deserializeMethod.Invoke(serializer, new[] { rawResult[item.ParameterName] });
}
}