使用C#[不确定对象名称]解析JSON

时间:2016-01-17 05:56:51

标签: c# json

我将使用C#和Newtonsoft.Json将JSON数据解析为类。但JSON数据与平常略有不同。 这是JSON数据样本:

{
    "ip_addresses": [
        "192.168.1.1"
     ],
    "ptr": {
        "192.168.1.1": "www.example.com"
    }
}

所以问题是由于ip_addresses中的IP ,ptr中的IP发生了变化。我已成功将ip_addresses数据解析为List。但我不知道下一步如何使用List存储的IP地址。

class Server
{
    public string hostname { get; set; }
    public List<string> ip_addresses { get; set; }
    public override string ToString() 
    {
        string ip_set = string.Empty;
        foreach (string ip in ip_addresses)
        {
            ip_set += string.Format("{0} ", ip);
        }
        return string.Format("{0} {1}\n", hostname, ip_set)
    }
}
class Program
{
    static void Main(string[] args)
    {
        //json data is from the web response
        string responseContent = reader.ReadToEnd();
        Server server = JsonConvert.DeserializeObject<Server>(responseContent);

        Console.WriteLine(server);
        Console.ReadKey();
    }
}

非常感谢:D

1 个答案:

答案 0 :(得分:5)

猜测ptr不是数组 然后,以下属性可能会起作用

public Dictionary<string,string> ptr {get; set;} 

如果是数组,则将其设为List<Dictionary<string,string>>

我在移动设备上,没有检查过它。请验证

更新:忘记添加
使用ptr["ipAddress"]

访问它