1. get JSON responses and go to :

  http://json2csharp.com/

2. write data contracts using C#

All classes need to have a DataContract attribute, and all public properties that are to be serialized need to have a DataMember attribute, and both a getter and a setter in C#

using System.Runtime.Serialization;

3. serialize the data against data contracts

The benefit of working with JSON serialization rather than XML serialization is that changes in the schema rarely cause issues for existing applications. For instance, if a new property is added to the REST Services, an application that uses the old data contracts can still process a response without errors; however, the new property will not be available. To get the new property, you must update the data contracts.

4. make HTTP Get request


using System;
using System.Net;
using System.Runtime.Serialization.Json; namespace RESTServicesJSONParserExample {
class Program
{
static string BingMapsKey = "insertYourBingMapsKey";
static void Main(string[] args)
{
try
{
string locationsRequest = CreateRequest("New%20York");
Response locationsResponse = MakeRequest(locationsRequest);
ProcessResponse(locationsResponse);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.Read();
} } //Create the request URL
public static string CreateRequest(string queryString)
{
string UrlRequest = "http://dev.virtualearth.net/REST/v1/Locations/" +
queryString +
"?key=" + BingMapsKey;
return (UrlRequest);
} public static Response MakeRequest(string requestUrl)
{
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
Response jsonResponse
= objResponse as Response;
return jsonResponse;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
} } static public void ProcessResponse(Response locationsResponse)
{ int locNum = locationsResponse.ResourceSets[0].Resources.Length; //Get formatted addresses: Option 1
//Get all locations in the response and then extract the formatted address for each location
Console.WriteLine("Show all formatted addresses");
for (int i = 0; i < locNum; i++)
{
Location location = (Location)locationsResponse.ResourceSets[0].Resources[i];
Console.WriteLine(location.Address.FormattedAddress);
}
Console.WriteLine(); //Get the Geocode Points for each Location
for (int i = 0; i < locNum; i++)
{
Location location = (Location)locationsResponse.ResourceSets[0].Resources[i];
Console.WriteLine("Geocode Points for "+location.Address.FormattedAddress);
int geocodePointNum = location.GeocodePoints.Length;
for (int j = 0; j < geocodePointNum; j++)
{
Console.WriteLine(" Point: "+location.GeocodePoints[j].Coordinates[0].ToString()+","+
location.GeocodePoints[j].Coordinates[1].ToString());
double test = location.GeocodePoints[j].Coordinates[1];
Console.Write(" Usage: ");
for (int k = 0; k < location.GeocodePoints[j].UsageTypes.Length; k++)
{
Console.Write(location.GeocodePoints[j].UsageTypes[k].ToString()+" ");
}
Console.WriteLine("\n\n");
}
}
Console.WriteLine(); //Get all locations that have a MatchCode=Good and Confidence=High
Console.WriteLine("Locations that have a Confidence=High");
for (int i = 0; i < locNum; i++)
{
Location location = (Location)locationsResponse.ResourceSets[0].Resources[i];
if (location.Confidence == "High")
Console.WriteLine(location.Address.FormattedAddress);
}
Console.WriteLine(); Console.WriteLine("Press any key to exit");
Console.ReadKey(); }
}
}

How parse REST service JSON response的更多相关文章

  1. 使用Groovy处理SoapUI中Json response

    最近工作中,处理最多的就是xml和json类型response,在SoapUI中request里面直接添加assertion处理json response的话,可以采用以下方式: import gro ...

  2. JavaScript -- JSON.parse 函数 和 JSON.stringify 函数

    JavaScript -- JSON.parse 函数 和 JSON.stringify 函数 1. JSON.parse 函数: 使用 JSON.parse 可将 JSON 字符串转换成对象. &l ...

  3. 【SoapUI】比较Json response

    package direct; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject ...

  4. datatable fix error–Invalid JSON response

    This error is pretty common. Meaning:When loading data by Ajax(ajax|option).DataTables by default, e ...

  5. [SoapUI] 重载JSONComparator比对JSON Response,忽略小数点后几位,将科学计数法转换为普通数字进行比对,在错误信息中打印当前循环的case number及其他附加信息

    重载JSONComparator比对JSON Response,忽略小数点后几位,将科学计数法转换为普通数字进行比对,在错误信息中打印当前循环的case number及其他附加信息 package d ...

  6. [Backbone] Parse not formatted JSON code

    The good Dr. recently had another team implement the server and they slightly messed up the format o ...

  7. 使用JSON.parse()转化成json对象需要注意的地方

    http://blog.csdn.net/u011277123/article/details/53055479 有三种方法: var str = '{"name":"小 ...

  8. [SoapUI] Compare JSON Response(比较jsonobject)

    http://jsonassert.skyscreamer.org/ 从这个网站下载jsonassert-1.5.0.jar ,也可以下载到源代码 JSONObject data = getRESTD ...

  9. [JSON] Validating/Asserting JSON response with Jsonlurper

    import groovy.json.JsonSlurper def response = messageExchange.response.responseContent log.info &quo ...

随机推荐

  1. 谈谈网站插入youtube视频播放

    最近需要在网页首页追加视频播放功能. 需要播放youtube视频.中间遇到一些波折.特来分享一下. 首先像网页添加视频文件我们通常够采用embed标签. 标签里可以设置很多的关键子.我们可以配置为fl ...

  2. C字符数组赋值(转)

    举例如下: char a[10];1.定义的时候直接用字符串赋值char a[10]="hello";注意:不能先定义再给它赋值,如 char a[10]; a[10]=" ...

  3. 智能车学习(十三)——角度控制

    一.手册代码以及图示 二.流程说明 1.角度计算函数说明 //===================================================================== ...

  4. 用eclipse开发和调试postgresql-8.4.1

    按照书本<PostgreSQL数据库内核分析>根据第一章讲解的linux下,编译 安装:不同的是libreadline5-dev版本没有了,就用新的版本代替:我的ubuntu 14 所以必 ...

  5. 【MongoDB】2.可视化工具的安装和使用

    首先:关于  能支持MongoDB新版本的可视化工具,争议不断,各人都有各人的支持. 因此之前选择安装的时候就安装了MongoDB  3.0.14版本的. 最终,确定使用Robomongo作为我第一个 ...

  6. express-10 表单处理

    从用户那里收集信息的常用方法就是使用HTML表单.无论是使用浏览器提交表单,还是使用AJAX提交,或是运用精巧的前端控件,底层机制通常仍旧是HTML表单. 向服务器发送客户端数据 向服务器发送客户端数 ...

  7. BZOJ 2002 [Hnoi2010]Bounce 弹飞绵羊 ——Link-Cut Tree

    [题目分析] 以前用分块的方法做过这道题目,现在再用LCT水一边,发现思路确实巧妙. 每次弹射,可以看作在一条边上走了过去,而且很重要的性质,每一个点的出边只有一条. 那么就很容易知道,可以用LCT维 ...

  8. 餐厅系统app7

    团队贡献分 杨子健:23 郭志豪:24 谭宇森:22 刘森松:31

  9. EF框架step by step(3)—Code-First

    CodeFirst是EF框架的第三种方式,也是最为复杂一种方式,本文将以EF4.1版本为基础,简要讲解一下用法,同时,也介绍DbContext的用法. 本文采用的示例仍然是前两篇采用的博客用户的示例. ...

  10. varchar和Nvarchar区别

    http://www.cnblogs.com/yelaiju/archive/2010/05/29/1746826.html Unicode字符集就是为了解决字符集这种不兼容的问题而产生的,它所有的字 ...