2016-01-03 65 views
1

我写了一个csharp应用程序,它查询我们的负载均衡器(它们在主动/被动配置中设置)以确定哪个是活动的。负载均衡有一个REST API,它我查询这样:C#反序列化JSON响应

public void GetActiveLB() 
{ 
    // Create a new RestClient and RestRequest 
    var client = new RestClient("https://myloadbalancer.domain.local"); 
    var request = new RestRequest("mgmt/tm/cm/failover-status", Method.GET); 

    // Specify authentication 
    client.Authenticator = new HttpBasicAuthenticator("myusername", "supersecret"); 

    // ask for the response to be in JSON syntax 
    request.RequestFormat = DataFormat.Json; 

    //send the request to the web service and store the response when it comes back 
    var queryResult = client.Execute(request); 

    // Create a new Deserializer to be able to parse the JSON object 
    RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer(); 
    var JSONObj = deserial.Deserialize<Dictionary<string, string>>(queryResult); 
    string lbstatus = JSONObj["description"]; 
} 

的JSON还给我看起来是这样的:

{ 
    "kind":"tm:cm:failover-status:failover-statusstats", 
    "selfLink":"https://localhost/mgmt/tm/cm/failover-status?ver=11.6.0", 
    "entries": { 
     "https://localhost/mgmt/tm/cm/failover-status/0": { 
      "nestedStats": { 
       "entries": { 
        "color": { 
         "description": "green" 
        }, 
       "https://localhost/mgmt/tm/cm/failoverStatus/0/details": { 
       "nestedStats": { 
        "entries": { 
         "https://localhost/mgmt/tm/cm/failoverStatus/0/details/0": { 
          "nestedStats": { 
           "entries": { 
            "details": { 
             "description": "active for /Common/traffic-group-1" 
            } 
           } 
          } 
         } 
        } 
       } 
      }, 
      "status": { 
       "description": "ACTIVE" 
      }, 
      "summary": { 
       "description": "1/1 active" 
      } 
     } 
    } 
} 
}} 

这里有一个漂亮格式化版本:enter image description here

我想要的物品的路径是:

[JSON].entries.https://localhost/mgmt/tm/cm/failover-status/0.nestedStats.entries.status.description 

我在努力的是如何以获得这个项目的价值,特别是因为它似乎嵌套多次。有没有办法提供绝对路径?

谢谢 布拉德

回答

0

做到这一点是使用dynamic关键词中最简单的方法:

dynamic JSONObj = 
    deserial 
    .Deserialize<Dictionary<string, object>>(queryResult); //Notice how I am using Dictionary<string, object> instead of Dictionary<string, string> since some of the values are actually parents of other values so they will be presented as dictionaries themselves. 

var lbstatus = 
    JSONObj 
     ["entries"] 
     ["https://localhost/mgmt/tm/cm/failover-status/0"] 
     ["nestedStats"] 
     ["entries"] 
     ["status"] 
     ["description"]; 

如果不使用dynamic关键字,那么你就必须投JSONObj["entries"]Dictionary<string,object>,然后当您访问该字典上的["https://localhost/mgmt/tm/cm/failover-status/0"]时,您需要将结果再次投入到Dictionary<string,object>中......等等。

在这种情况下,dynamic关键字将使其变得非常容易。

如果你想从一个绝对路径得到的结果,你可以做这样的事情与dynamic

dynamic JSONObj = deserial.Deserialize<Dictionary<string, object>>(queryResult); 

string path = 
    "entries.https://localhost/mgmt/tm/cm/failover-status/0.nestedStats.entries.status.description"; 

dynamic value = JSONObj; 

foreach (var sub_path in path.Split('.')) 
{ 
    value = value[sub_path]; 
} 

var lbstatus = value.ToString(); 
+0

谢谢 - 这个作品很棒! – Brad

1

如果JSON是始终结构相同的方式,你可以创建一些POCO的筑巢自己和然后用JSON deserialisation deserialise: 如:

[DataContract] 
public class JsonResponse 
{ 
    [datamember] 
    public string kind; 
    [datamember] 
    public string selflink; 
    [datamember] 
    public Entry entries; //we nest another object here just as in the json 
} 

[DataContract] 
public class Entry 
{ 
    [datamember] 
    public nestedstat nestedstats; 
} 

(这仅仅是松耦合类型)

则:

JsonResponse response = new JavaScriptSerializer().Deserialize<JsonResponse>(jsonasstring);