本文整理汇总了C#中System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject方法的典型用法代码示例。如果您正苦于以下问题:C# System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject方法的具体用法?C# System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject怎么用?C# System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Web.Script.Serialization.JavaScriptSerializer
的用法示例。
在下文中一共展示了System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CallPageTabs
public string CallPageTabs(string PageID)
{
//now we have page_id, redirect user to PAGE URL
string PageName = string.Empty;
//use FQL to get page name etc
StringBuilder oSBPgaeCaller = new StringBuilder();
oSBPgaeCaller.Append("https://api.facebook.com/method/fql.query?");
oSBPgaeCaller.Append("query=SELECT name FROM page WHERE page_id = " + PageID);
//oSBPgaeCaller.Append("&access_token=" + Session["user_access_token"].ToString());
oSBPgaeCaller.Append("&format=JSON");
FaceBook objFB = new FaceBook();
//Parse json to get MXDBAppUser
string _sUserInfoJson = objFB.CallWebRequest("GET", oSBPgaeCaller.ToString(), string.Empty);
object[] oUserLocationDataRow = new object[5];
//Convert Json to JsonDictionary <of String, object>
System.Web.Script.Serialization.JavaScriptSerializer _oJavaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
object _oJSONObject = _oJavaScriptSerializer.DeserializeObject(_sUserInfoJson);
int i = 0;
for (i = 0; i <= ((object[])_oJSONObject).Length - 1; i++)
{
Dictionary<string, object> _ojsonUserDetails = (Dictionary<string, object>)((object[])_oJSONObject)[i];
foreach (KeyValuePair<string, object> _oKeyjsonUserDetailsItem in _ojsonUserDetails)
{
switch (_oKeyjsonUserDetailsItem.Key)
{
case "name": //set Email
PageName = Convert.ToString(_oKeyjsonUserDetailsItem.Value);
break;
}
}
}
return PageName;
}
示例2: CallApi
static System.Collections.ICollection CallApi(String api)
{
Preferences prefs = Preferences.load ();
System.Net.WebClient webClient = new System.Net.WebClient ();
webClient.Headers.Set (System.Net.HttpRequestHeader.Accept, "application/json");
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer ();
String rawOutput = webClient.DownloadString ("https://circleci.com/api/v1" + api + "?circle-token=" + prefs.token);
System.Collections.ICollection result = (System.Collections.ICollection) serializer.DeserializeObject (rawOutput);
return result;
}
示例3: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
var anony = new { a = 1, b = "2",c=0.1,d=new[]{1,2,3} };
var jsonserialize = new System.Web.Script.Serialization.JavaScriptSerializer();
var obj=jsonserialize.DeserializeObject(jsonserialize.Serialize(anony));
Response.Write((obj as IDictionary)["c"]);
}
示例4: FromJson
public dynamic FromJson()
{
if (!IsJson)
throw new InvalidOperationException("This is not a json request. (ContentType='" + ContentType + "')");
var serializer = new JSSerializer();
var obj = serializer.DeserializeObject(GetString());
var dict = obj as IDictionary<String, Object>;
if (dict != null)
return new JsStore(dict);
return obj;
}
示例5: FromJSON
public static object FromJSON(string json)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer
= new System.Web.Script.Serialization.JavaScriptSerializer();
object jsonObj = serializer.DeserializeObject(json);
if (jsonObj == null)
return null;
if (typeof(IDictionary<string, object>).IsInstanceOfType(jsonObj))
return FromDictionary((IDictionary<string, object>)jsonObj);
else if (typeof(object[]).IsInstanceOfType(jsonObj))
return FromArray((object[])jsonObj);
return jsonObj;
}
示例6: FathersTest
// Note: fathers.json.txt was generated using:
// http://experiments.mennovanslooten.nl/2010/mockjson/tryit.html
// avg: file size ~ parse exec time (on Lenovo Win7 PC, i5, 2.50GHz, 6Gb)
// small.json.txt... avg: 4kb... parsed in ~1ms
// fathers.json.txt... avg: 12mb... parsed in ~3sec (30k msg... => 10k msg/sec)
// huge.json.txt... avg: 180mb... parsed in ~20sec
public static void FathersTest()
{
Console.Clear();
string json = System.IO.File.ReadAllText(FATHERS_TEST_FILE_PATH);
Console.WriteLine("Fathers Test - JSON parse... {0} kb ({1} mb)", (int)(json.Length / 1024), (int)(json.Length / (1024 * 1024)));
Console.WriteLine();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer
{
MaxJsonLength = int.MaxValue
};
Console.WriteLine("\tParsed by {0} in...", serializer.GetType().FullName);
DateTime start1 = DateTime.Now;
var msObj = serializer.DeserializeObject(json);
Console.WriteLine("\t\t{0} ms", (int)DateTime.Now.Subtract(start1).TotalMilliseconds);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("\tParsed by {0} in...", typeof(Parser).FullName);
DateTime start2 = DateTime.Now;
var myObj = JSON.Map(null as object).FromJson(json);
Console.WriteLine("\t\t{0} ms", (int)DateTime.Now.Subtract(start2).TotalMilliseconds);
Console.WriteLine();
Console.WriteLine("Press '1' to inspect our result object,\r\nany other key to inspect Microsoft's JS serializer result object...");
var parsed = ((Console.ReadKey().KeyChar == '1') ? myObj : msObj);
IList<object> fathers = parsed.Object()["fathers"].Array();
Console.WriteLine();
Console.WriteLine("Found : {0} fathers", fathers.Count);
Console.WriteLine();
Console.WriteLine("Press a key to list them...");
Console.WriteLine();
Console.ReadKey();
Console.WriteLine();
foreach (object father in fathers)
{
var name = (string)father.Object()["name"];
var sons = father.Object()["sons"].Array();
var daughters = father.Object()["daughters"].Array();
Console.WriteLine("{0}", name);
Console.WriteLine("\thas {0} son(s), and {1} daughter(s)", sons.Count, daughters.Count);
Console.WriteLine();
}
Console.WriteLine("Press a key...");
Console.ReadKey();
}
示例7: ParseMessage
private static IDictionary<string, object> ParseMessage(string line)
{
System.Diagnostics.Debug.Assert( !string.IsNullOrEmpty(line), "Missing parameter 'line'" );
System.Diagnostics.Debug.Assert( !line.Contains('\n'), "JSon serialized messages are not supposed to contain \\n" );
var deserializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var msg = (IDictionary<string,object>)deserializer.DeserializeObject( line );
return msg;
}
示例8: DeserializeItemsJson
private IEnumerable<UnreadItem> DeserializeItemsJson(string data, Func<string, bool> checkAction)
{
LogWriter.WriteTextToLogFile("Starting to deserialize items JSON from Google");
List<UnreadItem> returnValues = new List<UnreadItem>();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = data.Length;
var obj = serializer.DeserializeObject(data) as Dictionary<string,object>;
if (obj != null)
{
string ownUserId = obj["id"].ToString();
char[] separators = {'/'};
string[] temp = ownUserId.Split(separators);
if(temp.Length > 2) {
ownUserId = temp[1];
}
var itemsCollection = obj["items"] as object[];
if (itemsCollection != null)
{
foreach (var i in itemsCollection)
{
var item = i as Dictionary<string, object>;
if (item != null)
{
LogWriter.WriteTextToLogFile("Start parsing next entry");
string itemId = item["id"].ToString();
LogWriter.WriteTextToLogFile("Item ID is " + itemId);
if (!checkAction(itemId))
{
LogWriter.WriteTextToLogFile("This item is already in the list of known items");
continue;
}
string summaryContent = string.Empty;
string enclosureContent = string.Empty;
LogWriter.WriteTextToLogFile("Parsing summary");
if (item.ContainsKey("summary"))
{
LogWriter.WriteTextToLogFile("Item contains key summary");
var summary = item["summary"] as Dictionary<string, object>;
summaryContent = summary["content"].ToString();
}
else if(item.ContainsKey("content"))
{
LogWriter.WriteTextToLogFile("Item contains key content");
var summary = item["content"] as Dictionary<string, object>;
summaryContent = summary["content"].ToString();
}
bool liked = false;
int likingUsersNumber = 0;
LogWriter.WriteTextToLogFile("Parsing likingUsers");
if (item.ContainsKey("likingUsers"))
{
List<string> listOfLikingUser = new List<string>();
var lObjList = item["likingUsers"] as object[];
foreach (var l in lObjList)
{
LogWriter.WriteTextToLogFile("Parsing single likingUsers entry");
var likingUser = l as Dictionary<string, object>;
listOfLikingUser.Add(likingUser["userId"].ToString());
}
likingUsersNumber = listOfLikingUser.Count();
}
List<string> userLabels = new List<string>();
List<string> readerApiTages = new List<string>();
List<string> categories = new List<string>();
bool starred = false;
bool shared = false;
bool keptUnread = false;
LogWriter.WriteTextToLogFile("Starting parsing categories");
if (item.ContainsKey("categories"))
{
LogWriter.WriteTextToLogFile("Item categories available");
var lObjList = item["categories"] as object[];
foreach (string category in lObjList)
{
LogWriter.WriteTextToLogFile("Category is " + category);
if(category.StartsWith("user")) {
string[] tempArray = category.Split('/');
if (tempArray.Length > 2)
{
LogWriter.WriteTextToLogFile("It is category user - array has a length of " + tempArray.Length);
if (tempArray[tempArray.Length - 2] == "label")
{
LogWriter.WriteTextToLogFile("It is a label");
userLabels.Add(tempArray[tempArray.Length - 1]);
}
else
{
LogWriter.WriteTextToLogFile("It is a tag");
readerApiTages.Add(tempArray[tempArray.Length - 1]);
//.........这里部分代码省略.........
示例9: google_auth
public ActionResult google_auth(string code)
{
ElmcityApp.logger.LogHttpRequest(this.ControllerContext);
var auth = Authentications.AuthenticationList.Find(x => x.mode == Authentication.Mode.google);
var google_client_id = settings["google_client_id"];
var google_client_secret = settings["google_client_secret"];
var redirect_uri = settings["google_redirect_uri"];
if (code == null)
{
var redirect = String.Format("https://accounts.google.com/o/oauth2/auth?client_id={0}&scope={1}&response_type=code&redirect_uri={2}",
google_client_id,
Uri.EscapeUriString("https://www.google.com/calendar/feeds/"),
redirect_uri);
return new RedirectResult(redirect);
}
if (Request.Cookies[auth.cookie_name.ToString()] == null)
{
var cookie = new HttpCookie(auth.cookie_name.ToString(), DateTime.UtcNow.Ticks.ToString());
Response.SetCookie(cookie);
}
var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var post_data = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
Uri.EscapeUriString(code),
Uri.EscapeUriString(google_client_id),
Uri.EscapeUriString(google_client_secret),
Uri.EscapeUriString(redirect_uri)
);
var r = HttpUtils.DoHttpWebRequest(request, Encoding.UTF8.GetBytes(post_data));
string access_token = null;
try
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var dict = (Dictionary<string, object>)serializer.DeserializeObject(r.DataAsString());
access_token = (string)dict["access_token"];
}
catch (Exception e)
{
GenUtils.PriorityLogMsg("exception", "google_auth", e.Message + ", " + r.DataAsString());
}
var owncalendars = new Uri("https://www.google.com/calendar/feeds/default/owncalendars/full?access_token=" + Uri.EscapeUriString(access_token));
r = HttpUtils.FetchUrl(owncalendars);
string email = null;
var s = r.DataAsString();
var addrs = GenUtils.RegexFindGroups(s, "<author><name>[^>]+</name><email>([^>]+)</email></author>");
email = addrs[1];
if (email != null)
{
var session_id = Request.Cookies[auth.cookie_name.ToString()].Value;
Authentication.RememberUser(Request.UserHostAddress, Request.UserHostName, session_id, auth.mode.ToString(), auth.trusted_field.ToString(), email);
}
return new RedirectResult("/");
}
示例10: synchronize_data
/// <summary>
/// Synchronize data is called by the javascript preparser to get an ready to use JSON parsed data. If the dat can't be parsed as JSON
/// it will be returned as an common string
/// </summary>
/// <param name="uri">The address to the remote information to retrieve</param>
/// <returns></returns>
public object synchronize_data(string uri)
{
// Create web request
WebClient WC = new WebClient();
/**
* Try getting data. If no data was got an all, return FALSE
* */
try
{
String jsonRaw = WC.DownloadString(new Uri(uri));
// Convert it to JSON
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(jsonRaw);
return xmlDoc;
}
catch
{
return jsonRaw;
}
#if(obsolote)
try
{
Jint.JintEngine Engine = new JintEngine();
Jint.Native.JsObject D = new Jint.Native.JsObject((object)jsonRaw);
// Try parse it as json, otherwise try as xml and if not retuurn it as an string
try
{
// Do not allow CLR when reading external scripts for security measurements
System.Web.Script.Serialization.JavaScriptSerializer d = new System.Web.Script.Serialization.JavaScriptSerializer();
object json = d.DeserializeObject(jsonRaw);
return json;
}
catch
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(jsonRaw);
return xmlDoc;
}
}
catch
{
return jsonRaw;
}
#endif
}
catch
{
return false;
}
}
示例11: LOG
IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, object asyncState)
{
LOG( "BeginProcessRequest() - Start" );
ASSERT( MessageHandler != null, "Property 'MessageHandler' is not defined" );
ASSERT( ConnectionList != null, "Property 'ConnectionList' is not defined" );
RootMessage responseMessage;
string sessionID;
string connectionID = null;
bool connectionHeld = false; // Set to true if this ConnectionID has been held to receive the arriving messages
try
{
// Get SessionID
sessionID = LongPolling.ConnectionList.GetSessionID( context );
// Read request
var binData = context.Request.BinaryRead( context.Request.TotalBytes );
var strData = System.Text.UTF8Encoding.UTF8.GetString( binData );
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var requestMessage = (Dictionary<string,object>)serializer.DeserializeObject( strData );
// Check message type
string messageType = (string)requestMessage[ RootMessage.TypeKey ];
LOG( "BeginProcessRequest() - Received message of type '" + messageType + "'" );
switch( messageType )
{
case RootMessage.TypeInit: {
bool initAccepted = ConnectionList.CheckInitAccepted( requestMessage, sessionID );
if( initAccepted )
{
// Allocate a new ConnectionID and send it to the peer
connectionID = ConnectionList.AllocateNewConnectionID( sessionID );
responseMessage = RootMessage.CreateInitRootMessage( connectionID );
LOG( "BeginProcessRequest() - Response message set to 'init'" );
}
else
{
// Init refused => Send 'logout'
responseMessage = RootMessage.CreateLogoutRootMessage();
LOG( "BeginProcessRequest() - Response message set to 'logout'" );
}
break; }
case RootMessage.TypePoll: {
// Get ConnectionID
connectionID = requestMessage.TryGetString( RootMessage.KeySenderID );
if( string.IsNullOrEmpty(connectionID) )
throw new ApplicationException( "Missing sender ID in message" );
if(! ConnectionList.CheckConnectionIsValid(sessionID, connectionID) )
{
LOG( "BeginProcessRequest() *** The SessionID/ConnectionID could not be found in the ConnectionList. Sending Logout message" );
responseMessage = RootMessage.CreateLogoutRootMessage();
break;
}
// Register this connection for this ConnectionID
responseMessage = null;
// Don't set checkPendingMessages to true: Don't pull the messages from the MessageHandler right now but let it get registered to the ConnectionList first.
// So under heavy load, if there are always pending messages available each time the polling request reaches the server,
// the whole connection doesn't get timed-out because it never had the opportunity to register...
break; }
case RootMessage.TypeMessages: {
// Get ConnectionID
connectionID = requestMessage.TryGetString( RootMessage.KeySenderID );
if( string.IsNullOrEmpty(connectionID) )
throw new ApplicationException( "Missing ConnectionID in message" );
if(! ConnectionList.CheckConnectionIsValid(sessionID, connectionID) )
{
LOG( "BeginProcessRequest() *** The SessionID/ConnectionID could not be found in the ConnectionList. Sending Logout message" );
responseMessage = RootMessage.CreateLogoutRootMessage();
break;
}
// Hold any messages that must be sent to this connection until all those messages are received
// so that reply messages are not sent one by one
LOG( "BeginProcessRequest() - Holding connection '" + connectionID + "'" );
connectionHeld = true;
MessageHandler.HoldConnectionMessages( connectionID );
foreach( var messageItem in ((IEnumerable)requestMessage[ RootMessage.KeyMessageMessagesList ]).Cast<IDictionary<string,object>>() )
{
Message message = null;
try
{
var receivedMessage = Message.CreateReceivedMessage( connectionID, messageItem );
LOG( "BeginProcessRequest() - Receiving message '" + receivedMessage + "'" );
MessageHandler.ReceiveMessage( receivedMessage );
}
catch( System.Exception ex )
{
LOG( "BeginProcessRequest() *** Exception (" + ex.GetType().FullName + ") while receiving message" );
// Send exception through MessageHandler so that we can continue to parse the other messages
//.........这里部分代码省略.........
示例12: RemoteSend
public RemoteObj RemoteSend(string method, string arg0 = null, string arg1 = null, string arg2 = null, string arg3 = null, string arg4 = null, string arg5 = null, string arg6 = null)
{
string s = (string)this.browser.Explorer.Document.InvokeScript("APIConn", new object[] { method, arg0, arg1, arg2, arg3, arg4, arg5, arg6 });
if (s == null) {
return null;
}
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var o = (Dictionary<string, object>) serializer.DeserializeObject(s);
RemoteObj ret = new RemoteObj(this, null);
ret.Parse(o);
return ret;
}
示例13: GetUserDetail
public AppUser GetUserDetail(string sUserID, string soauth_token, AppUser oDCAppUser)
{
if (string.IsNullOrEmpty(soauth_token)) throw new Exception("Specify valid access token.");
if (string.IsNullOrEmpty(sUserID)) throw new Exception("Specify valid userid.");
StringBuilder _sbUserInfoURL = new StringBuilder();
_sbUserInfoURL.Append("https://api.facebook.com/method/fql.query?query=");
_sbUserInfoURL.Append("SELECT name,pic,current_location,email,sex,birthday_date,friend_count FROM user WHERE uid =");
_sbUserInfoURL.Append("'" + sUserID + "'");
_sbUserInfoURL.Append("&access_token=" + soauth_token);
_sbUserInfoURL.Append("&format=JSON");
//Parse json to get MXDBAppUser
string _sUserInfoJson = CallWebRequest("GET", _sbUserInfoURL.ToString(), string.Empty);
object[] oUserLocationDataRow = new object[7];
//Convert Json to JsonDictionary <of String, object>
System.Web.Script.Serialization.JavaScriptSerializer _oJavaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
object _oJSONObject = _oJavaScriptSerializer.DeserializeObject(_sUserInfoJson);
int i = 0;
for (i = 0; i <= ((object[])_oJSONObject).Length - 1; i++)
{
Dictionary<string, object> _ojsonUserDetails = (Dictionary<string, object>)((object[])_oJSONObject)[i];
foreach (KeyValuePair<string, object> _oKeyjsonUserDetailsItem in _ojsonUserDetails)
{
switch (_oKeyjsonUserDetailsItem.Key)
{
case "name": //set Email
oDCAppUser.UserName = Convert.ToString(_oKeyjsonUserDetailsItem.Value);
break;
case "pic": //set User name
oDCAppUser.ImageURL = Convert.ToString(_oKeyjsonUserDetailsItem.Value);
break;
case "email": //set contact email
oDCAppUser.EmailID = Convert.ToString(_oKeyjsonUserDetailsItem.Value);
break;
case "current_location": // set current location
if (_oKeyjsonUserDetailsItem.Value != null && Convert.ToString(_oKeyjsonUserDetailsItem.Value).Length > 0)
{
//set location fields
Dictionary<string, object> jsonlocationDict = (Dictionary<string, object>)_oKeyjsonUserDetailsItem.Value;
foreach (KeyValuePair<string, object> _olocationItem in jsonlocationDict)
{
switch (_olocationItem.Key.ToLower())
{
case "city":
if (Convert.ToString(_olocationItem.Value).Length > 0)
{
string[] _olocationvalue = Convert.ToString(_olocationItem.Value).Split(new string[] { "," }, StringSplitOptions.None);
if (_olocationvalue.Length >= 1) oDCAppUser.City = _olocationvalue[0];
}
break;
case "state":
if (Convert.ToString(_olocationItem.Value).Length > 0)
{
string[] _olocationvalue = Convert.ToString(_olocationItem.Value).Split(new string[] { "," }, StringSplitOptions.None);
if (_olocationvalue.Length >= 1) oDCAppUser.State = _olocationvalue[0];
}
break;
case "country":
if (Convert.ToString(_olocationItem.Value).Length > 0)
{
string[] _olocationvalue = Convert.ToString(_olocationItem.Value).Split(new string[] { "," }, StringSplitOptions.None);
if (_olocationvalue.Length >= 1) oDCAppUser.Country = _olocationvalue[0];
}
break;
default:
break; //Could not parse location json element
}
}
}
break;
case "sex": oDCAppUser.Gender = Convert.ToString(_oKeyjsonUserDetailsItem.Value);
break;
case "birthday_date": oDCAppUser.SBirthdate = Convert.ToString(_oKeyjsonUserDetailsItem.Value);
break;
case "friend_count": oDCAppUser.SFriend_count = Convert.ToString(_oKeyjsonUserDetailsItem.Value);
break;
}
}
}
return oDCAppUser;
}
示例14: GetFriendsDetail
public DataTable GetFriendsDetail(string sUserID, string soauth_token)
{
if (string.IsNullOrEmpty(soauth_token)) throw new Exception("Specify valid access token.");
if (string.IsNullOrEmpty(sUserID)) throw new Exception("Specify valid userid.");
StringBuilder _sbFriendInfoURL = new StringBuilder();
_sbFriendInfoURL.Append("https://api.facebook.com/method/fql.query?query=");
_sbFriendInfoURL.Append("SELECT uid,name,pic,sex,current_location,birthday_date FROM user WHERE uid in (select uid2 from friend where uid1=");
_sbFriendInfoURL.Append(sUserID + ")");
_sbFriendInfoURL.Append("&access_token=" + soauth_token);
_sbFriendInfoURL.Append("&format=JSON");
//Parse json to get MXDBAppUser
string _sFriendsInfoJson = CallWebRequest("GET", _sbFriendInfoURL.ToString(), string.Empty);
//Create DataTable
DataTable oFriendsTable = new DataTable("FriendsTable");
DataColumn osoNETID = new DataColumn("soNETID");
oFriendsTable.Columns.Add(osoNETID);
DataColumn oImage = new DataColumn("Image");
oFriendsTable.Columns.Add(oImage);
DataColumn oName = new DataColumn("Name");
oFriendsTable.Columns.Add(oName);
DataColumn oLocation = new DataColumn("Location");
oFriendsTable.Columns.Add(oLocation);
DataColumn oGender = new DataColumn("Gender");
oFriendsTable.Columns.Add(oGender);
DataColumn oBithdate = new DataColumn("Birthdate");
oFriendsTable.Columns.Add(oBithdate);
//Convert Json to JsonDictionary <of String, object>
System.Web.Script.Serialization.JavaScriptSerializer _oJavaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
object _oJSONObject = _oJavaScriptSerializer.DeserializeObject(_sFriendsInfoJson);
int i = 0;
for (i = 0; i <= ((object[])_oJSONObject).Length - 1; i++)
{
Dictionary<string, object> _ojsonFriendDetails = (Dictionary<string, object>)((object[])_oJSONObject)[i];
//'Parse & Save individual friends details
object[] oFriendDataRow = new object[6];
foreach (KeyValuePair<string, object> _oKeyjsonFriendDetailsItem in _ojsonFriendDetails)
{
switch (_oKeyjsonFriendDetailsItem.Key)
{
case "uid": //set friendID
oFriendDataRow[0] = Convert.ToString(_oKeyjsonFriendDetailsItem.Value);
break;
case "name": //set User name
oFriendDataRow[2] = Convert.ToString(_oKeyjsonFriendDetailsItem.Value);
break;
case "pic": //set User picture
oFriendDataRow[1] = Convert.ToString(_oKeyjsonFriendDetailsItem.Value);
break;
case "sex": //set User picture
oFriendDataRow[4] = Convert.ToString(_oKeyjsonFriendDetailsItem.Value);
break;
case "current_location":
try
{
if (_oKeyjsonFriendDetailsItem.Value != null && Convert.ToString(_oKeyjsonFriendDetailsItem.Value).Length > 0)
{
//set location fields
Dictionary<string, object> jsonlocationDict = (Dictionary<string, object>)_oKeyjsonFriendDetailsItem.Value;
foreach (KeyValuePair<string, object> _olocationItem in jsonlocationDict)
{
switch (_olocationItem.Key.ToLower())
{
case "city":
if (Convert.ToString(_olocationItem.Value).Length > 0)
{
string[] _olocationvalue = Convert.ToString(_olocationItem.Value).Split(new string[] { "," }, StringSplitOptions.None);
if (_olocationvalue.Length >= 1) oFriendDataRow[3] += _olocationvalue[0] + ",";
}
break;
case "state":
if (Convert.ToString(_olocationItem.Value).Length > 0)
{
string[] _olocationvalue = Convert.ToString(_olocationItem.Value).Split(new string[] { "," }, StringSplitOptions.None);
if (_olocationvalue.Length >= 1) oFriendDataRow[3] += _olocationvalue[0] + ",";
}
break;
case "country":
if (Convert.ToString(_olocationItem.Value).Length > 0)
{
string[] _olocationvalue = Convert.ToString(_olocationItem.Value).Split(new string[] { "," }, StringSplitOptions.None);
if (_olocationvalue.Length >= 1) oFriendDataRow[3] += _olocationvalue[0];
}
break;
default:
break; //Could not parse location json element
}
}
}
}
catch (Exception ex)
{
//.........这里部分代码省略.........
示例15: NetJavascript
static void NetJavascript(string input, int max)
{
var s = new System.Web.Script.Serialization.JavaScriptSerializer();
for (var i = 0; i < max; i++)
{
s.DeserializeObject(input);
}
}