1

在这里,我有 json 字符串,我想从这个 json 字符串中获取一个特定的键和值。所以我为此使用了 javascript 序列化程序。下面是我在 C#.Net 中使用的代码。

string strProfile = fbApi.GetForStr("/statefarm/feed/");
var jss = new JavaScriptSerializer();
var dictionary = (IDictionary<string, object>)jss.DeserializeObject(strProfile);  
object keyvalue = (object)dictionary["paging"]; 
string data = keyvalue.ToString();

当我这样做时,我无法从 jsonstring 中获取 keyvale 对。如果我写

string keyvalue = (string)dictionary["paging"]; 

代替

object keyvalue = (object)dictionary["paging"]; 
string data = keyvalue.ToString();

遇到异常

'system.object'类型的对象类型'system.string'

为此要做什么以及如何编写。

4

1 回答 1

0

我假设您在此处使用一些 SDK/您的自定义代码来使用 Facebook API。JSON.NET是最好的方法,除非您不想最终陷入键值配对 JSON 的混乱局面。

尝试这个。

var api = new FacebookClient
{
    AccessToken = accessToken,
    AppId = AppID,
    AppSecret = AppSecret
};
dynamic result = api.Get("me/posts");
string JsonConvert.SerializeObject(result, new KeyValuePairConverter())

或为避免混淆,只需将其添加到您的代码中

object keyvalue = (object)dictionary["paging"];
JsonConvert.SerializeObject(keyvalue , new KeyValuePairConverter());

NewtonSoft.Json.dll也可作为 Nuget 包使用

于 2012-05-14T06:46:12.130 回答