【问题标题】:How to decode JSON in C#如何在 C# 中解码 JSON
【发布时间】:2012-03-15 00:24:53
【问题描述】:

我正在尝试使用来自 NewtonSoft.Json 的 JSONConvert 解码从 twitter 流 API 接收到的 JSON

我创建了这个类来模仿 twitter 状态对象

class tweeter
{
    public string geo { get; set; }
    public string text { get; set; }
    public string name { get; set; }
    public string screen_name { get; set; }
    public string created_at { get; set; }
    public string id { get; set; }

}

然后在我的代码中我执行以下操作来解码它

try
              {
                  System.Threading.Interlocked.Increment(ref linesRead);
                  var des = JsonConvert.DeserializeObject<tweeter>(e.Line);
                  listBox1.Items.Add(e.Line);

                  dbhelper.insertTweet(des.id,des.screen_name,des.text,des.created_at,"","","", com);

                  listBox1.SelectedIndex = listBox1.Items.Count - 1;

                  listBox1.SelectedIndex = -1;
                  label1.Text = string.Format("Lines Read: {0:F0}", linesRead);
              }
              catch (Exception x)
              {
                  MessageBox.Show(x.Message);
              }

但是,像 screen_name 这样的嵌套元素总是返回 null,我如何访问这些嵌套元素?

geo、text、created_at、id 等其他根元素正常返回并具有值。

ُEDIT:这是来自提要{"in_reply_to_status_id":null,"favorited":false,"text":"Haa I'm joking everyone I wish! Need it for #ibiza2012 and #Egypt","in_reply_to_status_id_str":null,"entities":{"hashtags":[{"text":"ibiza2012","indices":[44,54]},{"text":"Egypt","indices":[59,65]}],"urls":[],"user_mentions":[]},"geo":null,"retweet_count":0,"place":null,"truncated":false,"created_at":"Wed Mar 14 15:14:47 +0000 2012","in_reply_to_user_id_str":null,"source":"\u003Ca href=\"http:\/\/twitter.com\/#!\/download\/iphone\" rel=\"nofollow\"\u003ETwitter for iPhone\u003C\/a\u003E","retweeted":false,"in_reply_to_screen_name":null,"coordinates":null,"in_reply_to_user_id":null,"user":{"contributors_enabled":false,"geo_enabled":false,"profile_sidebar_fill_color":"DDEEF6","lang":"en","listed_count":0,"created_at":"Sat Apr 11 17:12:45 +0000 2009","profile_sidebar_border_color":"C0DEED","is_translator":false,"show_all_inline_media":true,"follow_request_sent":null,"verified":false,"url":null,"description":"Ibiza 2012 for openings! Have a bang on that!","default_profile":true,"following":null,"profile_use_background_image":true,"time_zone":null,"profile_text_color":"333333","statuses_count":2513,"notifications":null,"profile_background_image_url_https":"https:\/\/si0.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url":"http:\/\/a0.twimg.com\/images\/themes\/theme1\/bg.png","location":"London","profile_link_color":"0084B4","followers_count":350,"protected":false,"profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1895048740\/image_normal.jpg","profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1895048740\/image_normal.jpg","default_profile_image":false,"screen_name":"wyatt69","name":"Dean Wyatt","favourites_count":0,"profile_background_color":"C0DEED","id":30482455,"id_str":"30482455","profile_background_tile":false,"utc_offset":null,"friends_count":384},"id":179948698397196288,"id_str":"179948698397196288","contributors":null} d":false,"profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1673331511\/logo-for-twitter_normal.png","profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1673331511\/logo-for-twitter_normal.png","default_profile_image":false,"screen_name":"itwitex","name":"itwitex","favourites_count":0,"profile_background_color":"EBEBEB","id":307251688,"id_str":"307251688","profile_background_tile":false,"utc_offset":3600,"friends_count":0},"id":179948696308432896,"possibly_sensitive_editable":true,"possibly_sensitive":false,"id_str":"179948696308432896","contributors":null} 的样本

【问题讨论】:

  • Parsing JSON using Json.net 的可能重复项
  • 添加您从 twitter 获得的 JSON 数据。
  • 您能提供来自该提要的 JSON 样本吗?
  • 您的示例中是 JSON.NET 吗?你应该解释一下你目前的方法。
  • 你的第一个问题是嵌套数据,所以 Adam Gritt 的答案是你最好的选择。

标签: c# json


【解决方案1】:

我最近不得不为应用程序的一些内部测试做一些类似的事情。我用类似以下的方式处理了这种情况:

[DataContract]
class Tweeter
{
    [DataMember]
    public string geo {get;set;}
    [DataMember]
    public User user {get;set;}
}

[DataContract]
class User
{
    [DataMember]
    public string screen_name {get;set;}
}

class Converter
{
    public Tweeter ConvertJson(string json)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Tweeter));

        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            return serializer.ReadObject(ms) as Tweeter;
        }
    }
}

【讨论】:

  • 这是在 .net 4 中吗?因为我只能使用 .net 3.5
  • 我的代码是用 .NET 4 编写的,但 .NET 3.5 支持序列化程序 -- msdn.microsoft.com/en-us/library/…
  • Visual Studio 报告找不到 DataContract
  • 为此,您需要添加对 System.Runtime.Serialization.dll 的引用
  • 你确定最后一节课吗?看来这对我来说应该是一种方法,但可能是错误的
【解决方案2】:

您为什么不简单地使用JavaScriptSerializer.Deserialize 方法在System.Web.Script.Serialization 命名空间中反序列化json:

http://msdn.microsoft.com/en-us/library/ee191864.aspx

【讨论】:

  • 很抱歉,我目前无法使用 .net 4.0 =(
  • 那么按照 Adam Gritt 的回答使用 DataContractSerializer 可能是您最好的选择。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
相关资源
最近更新 更多