0

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

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

我只是想获取每个变量(或我需要的变量),将其存储在一个变量(字符串、int 等)中,然后在我的代码隐藏中使用它来做我需要的任何事情。另外,请注意我使用的是 ASP.NET 3.5 / C#。

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

4

3 回答 3

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;}
}

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

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

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

var facebookResponseItem = new FacebookResponse();
//some initial code here
var sendFacebookResponseItem = JsonConvert.SerializeObject(facebookResponseItem);
于 2013-10-31T09:52:52.513 回答
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"];
于 2013-10-31T08:25:04.567 回答
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 对象。

于 2013-10-31T08:33:07.863 回答