在ASP.NET 3.5中存储JSON对象的字段

时间:2013-10-31 07:43:21

标签: c# asp.net json facebook facebook-c#-sdk

我正在调用一个外部Web服务(Facebook API),它在我的一个页面后面的代码中返回一个JSON对象(见下文)。我试图找出在我的代码隐藏中存储来自此JSON对象的每个字段的最有效方法(实际上尝试获取一个字段,金额字段)。 JSON对象如下:

{"algorithm":"HMAC-SHA256","amount":"5.00","currency":"USD",
 "issued_at":81723498712,"payment_id":71283749753874,"quantity":"5",
 "status":"completed"}

我只想抓取每个变量(或我需要的变量),将其存储在变量(string,int等)中,然后将其用于我的代码隐藏中所需的任何内容。另请注意,我使用的是ASP.NET 3.5 / C#。

对此提出任何建议都会有所帮助。在此先感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

您可以使用Newtonsoft的Json.NET库。它使用起来非常简单。您可以在MSVS中使用NuGet软件包安装它,也可以从网站http://json.codeplex.com/

下载

然后你应该创建这样的类:

class FacebookResponse
{
    public string Algorithm {get;set;}
    public float Amount {get;set;}
    public string Currency {get;set;}
    public DateTime IssuedAt {get;set;}
    public string PaymentId {get;set;}
    public int Quantity {get; set;}
    public string Status {get;set;}
}

之后,当您从API收到JsonString时,可以使用以下方法:

FacebookResponse response = JsonConvert.DeserializeObject<FacebookResponse>(JsonString);

如果您需要使用JSON序列化该类,您可以使用:

var facebookResponseItem = new FacebookResponse();
//some initial code here
var sendFacebookResponseItem = JsonConvert.SerializeObject(facebookResponseItem);

答案 1 :(得分:0)

我明白了,代码如下:

var result = "Code for Call to Facebook Goes Here - Returns JSON Object";
string json = result.ToString();
var serializer = new JavaScriptSerializer(); 
Dictionary<string, string> values = serializer.Deserialize<Dictionary<string, string>>(json);
string amount = (string)values["amount"];

答案 2 :(得分:0)

    class Item{
      public string algorithm {get;set;}
      public float amount {get;set;}
      public string currency {get;set;}
      public Date issued_at {get;set;}
      public string payment_id {get;set;}
      public int quantity {get; set;}
      public string status {get;set;}

    }

   Item item = JSON.Deserialaize(JSON_OBJECT)  // check for specific syntax
   Item[] item = JSON.Deserialize(JSON_OBJECT) // even can get array of json objects

您现在可以按照自己想要的方式使用这些json对象。