如何解析动态JSON .net newtonsoft

时间:2013-02-26 14:43:11

标签: .net json windows-phone-8

我尝试过关注示例Parsing json in C# without knowing indexes。不过我仍然遇到错误:

  

Newtonsoft.Json.Linq.JObject'不包含ip_addresses的定义

我想要实现的是解析以下JSON并将每个ip地址添加到ObservableCollection。如果我知道密钥但IP地址可以命名为任何东西,那么通常情况下这一切都很顺利。

以下是我目前正在处理的代码以及IP地址拥有自己的类的原因是因为稍后在应用程序中还有很多工作要做。:

    try
    {
        dynamic jObj = JsonConvert.DeserializeObject(e.Result);
        foreach (var child in jObj.ip_addresses.Children())
        {
            ips.Add(new IpAddresses() { ip = child });
        }
    }
    catch
    {
        MessageBox.Show("Generic error message");
    }

    public class IpAddresses
    {
        public string ip { get; set; }
    }

这是JSON:

{
    "id": "reallysimpleid",
    "label": "server name",
    "ip_addresses": {
    "private0_v4": "100.100.100.100",
    "access_ip0_v4": "100.100.100.100",
    "public0_v6": "1000:1000:7805:0113:9073:8c63:1000:1000",
    "access_ip1_v6": "1000:1000:7805:0113:9073:8c63:1000:1000",
    "public1_v4": "100.100.100.100"
},
    "metadata": null,
    "managed": false,
    "uri": "https://www.awebsite.com",
    "agent_id": null,
    "created_at": 1360960027217,
    "updated_at": 1360960027217
}

2 个答案:

答案 0 :(得分:0)

你的课应该是这样的:

     public class IpAddresses
     {
     public string private0_v4 { get; set; }
     public string access_ip0_v4 { get; set; }
     public string public0_v6 { get; set; }
     public string access_ip1_v6 { get; set; }
     public string public1_v4 { get; set; }
     }

     public class RootObject
     {
     public string id { get; set; }
     public string label { get; set; }
     public IpAddresses ip_addresses { get; set; }
     public object metadata { get; set; }
     public bool managed { get; set; }
     public string uri { get; set; }
     public object agent_id { get; set; }
     public long created_at { get; set; }
     public long updated_at { get; set; }
     }

您的代码应为:

     jObj = JsonConvert.DeserializeObject<RootObject>(e.Result);

答案 1 :(得分:0)

child对象可能不是您想要的,因为它是JProperty对象;如果你所需要的只是字符串IP地址,那么使用:

ips.Add(new IpAddresses() { ip = child.Value.ToString() });