如何在c#中读取JSON响应

时间:2012-03-29 13:43:46

标签: c# .net json

我正在使用thirparty服务给我坐标,下面是我想在某种对象中使用c#.net读取的响应,这样我就可以使用这些信息但是如何实现这一点却很困惑..

{"found": 1, "bounds": [[52.45401, -1.96211], [52.45401, -1.96211]], "features": [{"id": 65140,"centroid": {"type":"POINT","coordinates":[52.45401, -1.96211]},"bounds": [[52.45401, -1.96211], [52.45401, -1.96211]],"properties": {"name": "B17 0SL"},"type": "Feature"}], "type": "FeatureCollection", "crs": {"type": "EPSG", "properties": {"code": 4326, "coordinate_order": [0, 1]}}}

由于

5 个答案:

答案 0 :(得分:2)

看看Newtonsoft.Json它是一个将Json反序列化为类的包。

但您需要创建要使用的类结构。

答案 1 :(得分:2)

使用json解析器,例如DataContractJsonSerializerJavaScriptSerializer

对于您的案例,请使用Json.Net& dynamic关键字,您可以写

dynamic jObj = JsonConvert.DeserializeObject(jsonstr);
Console.WriteLine(jObj.found);
Console.WriteLine(jObj.features[0].bounds[0][0]);

答案 2 :(得分:1)

您可以使用JsonTextReader。如果您不使用JSON.NET

,以下代码段可能会有用
jsonString = {"found": 1, "bounds": [[52.45401, -1.96211], [52.45401, -1.96211]], "features": [{"id": 65140,"centroid": {"type":"POINT","coordinates":[52.45401, -1.96211]},"bounds": [[52.45401, -1.96211], [52.45401, -1.96211]],"properties": {"name": "B17 0SL"},"type": "Feature"}], "type": "FeatureCollection", "crs": {"type": "EPSG", "properties": {"code": 4326, "coordinate_order": [0, 1]}}};
JsonTextReader reader = new JsonTextReader(new StringReader(jsonString));

while (reader.Read())
{
   if (reader.Value != null)
   {
      // Read Json values here
      // reader.Path               -> Gives you the key part.
      // reader.Value.ToString()   -> Gives you the value part
   }
}

答案 3 :(得分:1)

您可以像这样阅读JSON:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL");

            JArray array = new JArray();
            using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
            {

                using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
                {
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    var objText = reader.ReadToEnd();

                    JObject joResponse = JObject.Parse(objText);
                    JObject result = (JObject)joResponse["result"];
                    array = (JArray)result["Detail"];
                    string statu = array[0]["dlrStat"].ToString();
                }

            }

答案 4 :(得分:0)

您可以使用JSON.NET