這是我第一次嘗試反序列化Facebook返回的JSON字符串。
我想確保未來的開發人員能夠舒適地維護我的代碼,所以我想知道這是否可行。我擔心如果JSON字符串發生變化,我將需要重寫一些類。
從Facebook返回的JSON字符串可能會更改嗎?例如,如果位置成爲不同的對象,我將需要做出更改。這是反序列化Facebook JSON字符串的好方法嗎?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Web;
//--- If you are not able to add reference dont worry. You probably need to install ASP.NET Ajax or target higher .NET Framework (3.5 or 4).
//--- There are Stack Overflow threads about this.
using System.Web.Script.Serialization;
//--- Our Facebook Person class.
public class FBPerson
{
public string id { get; set; }
public string email { get; set; }
public string name { get; set; }
public string gender { get; set; }
public IDName location { get; set; }
public List<FBObject> work { get; set; }
public List<FBObject> education { get; set; }
}
//-- In some cases only id and name will be accessed
public class IDName
{
public string id { get; set; }
public string name { get; set; }
public string type { get; set; }
}
//-- work and education presently are array of json strings
public class FBObject
{
public IDName employer { get; set; }
public IDName school { get; set; }
}
static class Program
{
//-- Sample JSON string returned by Facebook
const string json2 = @"{
""id"":""11111111111111111"",
""name"":""Tester Test"",
""first_name"":""Tester"",
""last_name"":""Test"",
""link"":""http:\/\/www.facebook.com\/profile.php?id=11111111111111111"",
""location"":
{""id"":""107991659233606"",""name"":""Atlanta, Georgia""},
""work"":
[{""employer"":{""id"":""222222222222222222"",""name"":""Various""}}],
""education"":
[
{""school"":{""id"":""108000000000000"",""name"":""Test High School""},""type"":""High School""},
{""school"":{""id"":""105000000000000"",""name"":""Tester College""},""type"":""College""}
],
""gender"":""male"",
""email"":""tester\u0040gmail.com"",
""timezone"":-5,""locale"":""en_US"",
""verified"":true,
""updated_time"":""2011-11-21T21:10:20+0000""
}";
static void Main()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
FBPerson fperson = ser.Deserialize<FBPerson>(json2);
//-- Display the user info from the JSON string
Console.WriteLine(fperson.id.ToString());
Console.WriteLine(fperson.name.ToString());
Console.WriteLine(fperson.gender.ToString());
Console.WriteLine(fperson.email.ToString());
Console.WriteLine(fperson.location.name.ToString());
Console.WriteLine(fperson.work[0].employer.name.ToString());
Console.WriteLine(fperson.education[0].school.name.ToString());
Console.ReadLine();
}
}
人檢查此鏈接,此代碼是真棒:https://stackoverflow.com/questions/30411318/json-net-parse-facebook-graph-json-for-all-messages – 2017-10-10 09:38:09