2017-10-22 82 views
0

从一个RESTful API的响应返回一些JSON:提取值响应

{ 
    "meta": { 
    "href": "http://localhost:54398/" 
    }, 
    "busPartner": { 
    "href": "http://localhost:54398/BusPartner", 
    "rel": [ 
     "collection" 
    ] 
    }, 
    "busPartnerType": { 
    "href": "http://localhost:54398/BusPartnerType", 
    "rel": [ 
     "collection" 
    ] 
    }, 
    "busPartnerPossAttrib": { 
    "href": "http://localhost:54398/BusPartnerPossAttribs", 
    "rel": [ 
     "collection" 
    ] 
    } 
} 

我试图从中提取JSON href值的列表。虽然我可以按照以下使用JsonTextReader走我需要出结果列表中的数值...

IList<string> tt = new List<string>(); 
JsonTextReader reader = new JsonTextReader(new StringReader(response)); 
while (reader.Read()) 
{ 
    if (reader.Value != null) 
    { 
     tt.Add(reader.TokenType + " " + reader.Value); 
    } 
    else 
    { 
     tt.Add(reader.TokenType.ToString()); 
    } 
} 

...这是笨拙和繁琐。一定会有更好的办法。任何线索?

回答

0

您可以使用Json.Net的LINQ-to-JSON API(JObjects)提取列表:

List<string> tt = JObject.Parse(response) 
    .Descendants() 
    .OfType<JProperty>() 
    .Where(jp => jp.Name == "href" && jp.Value.Type == JTokenType.String) 
    .Select(jp => (string)jp.Value) 
    .ToList(); 

小提琴:https://dotnetfiddle.net/sAf26B

+0

感谢这已经让我完全步入正轨与我的项目的一部分,曾直副本和过去:) –