【问题标题】:.Net Parse JSON from Google.Net 解析来自 Google 的 JSON
【发布时间】:2018-02-12 12:57:55
【问题描述】:

所以我正在使用其中一个 google Id API; https://developers.google.com/instance-id/reference/server#manage_registration_tokens_for_push_subscriptions 我以前很幸运拥有具有 WDSL 或类似功能且易于解析为类的 API。 但是我得到的JSON我不能轻易解析。

 {
"connectDate":"2018-02-12",
"application":"com.chrome.windows",
"subtype":"wp:https://xxxxxxxxxxxxxxxxxxx",
"authorizedEntity":"xxxxxx",
"rel":{
    "topics":{
        "movies":{
            "addDate":"2018-01-26"
            },
        "anotherTopic":{    
            "addDate":"2018-02-12"
            }
        }
},
"connectionType":"WIFI",
"platform":"WEBPUSH"
} 

Movies 和 anotherTopics 是我创建的主题,因此我无法将它们添加到我的课程中。或者我可以吗?

当然有办法将 json 视为字符串并使用正则表达式或将节点作为动态对象 (dynamic dyn = JsonConvert.DeserializeObject(content);) 但理想情况下我认为它应该是字典 (我认为至少)但看不到如何。

由于这是 Google,我认为有更标准的方式来处理这种 JSON。

我尝试创建一个我无法使用的字典。 遍历节点我可以获得数据,但最终会得到类似

的代码
DateTime.Parse(((Newtonsoft.Json.Linq.JValue)((Newtonsoft.Json.Linq.JProperty)((Newtonsoft.Json.Linq.JContainer)(obj.First)).First).Value).Value.ToString()) 

我曾尝试寻找类似的 JSON 解析示例,但找不到。

我没有分享我在第一次编辑时提取数据的尝试,因为我认为这不是这样做的方法;这是一个黑客。

我为它创建了一个类

       public class SubscriptionDetails
{
    public DateTime connectDate { get; set; }
    public string application { get; set; }
    public string subtype { get; set; }
    public string authorizedEntity { get; set; }
    public string connectionType { get; set; }
    public string platform { get; set; }
    public topics rel { get; set; }
 } 

但是在定义子类主题时我被卡住了。

所以我尝试了

public class topics  : Dictionary<string, object>

这会导致一个包含关键主题的字典条目? 另一个选项需要字典名称

public class topics
{
    public Dictionary<string, Dictionary<string, string>> DUMMY { get; set; }
}

【问题讨论】:

  • 你在说什么课?
  • 忘了说我正在使用 C#。它正在解析我正在努力解决的“主题”节点。
  • topics 将是 Dictionary&lt;string,Dictionary&lt;string,string&gt;&gt;
  • 我很抱歉,但我真的不知道如何使用它。如果我将字典添加到类主题中,它需要一个名称: public class topics { public Dictionary> DUMMY { get;放;我能想到的公共课程主题的另一个选项: Dictionary> will not parse (get exception).
  • 你有一个根级属性 rel - 它需要是一个类,具有我在上面发布的字典类型的 1 个属性 topics

标签: c# json parsing


【解决方案1】:

感谢 Jamiec 的建议,我走上了正轨。 当然,节点 rel 已经是一个字典,其中包含一个名为 topic 的项目。

所以需要几个类来解析整个事情:

    public class SubscriptionDetails
{
    public DateTime connectDate { get; set; }
    public string application { get; set; }
    public string subtype { get; set; }
    public string authorizedEntity { get; set; }
    public string connectionType { get; set; }
    public string platform { get; set; }
    public Dictionary<string, topicItems>   rel { get; set; }
}

public class topicItems : Dictionary<string, topicData> { }
public class topicData
{
    public DateTime addDate { get; set; }
}

但是,如果他们除了“主题”之外还向 rel 添加另一个节点,这很可能会崩溃。 只是似乎不是构造数据的好方法,反序列化的类也不是很友好..

无论如何它都有效(目前)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    相关资源
    最近更新 更多