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. Thinkphp 解决写入配置文件的方法

    在/Application/Common/Common创建function.php,然后添加以下代码: <?php /** * [writeArr 写入配置文件方法] * @param [typ ...

  2. WPF中使用ReportViewer报表

    本篇博客将介绍如何在WPF中使用ReportViewer控件. 1. 环境准备:下载安装最新版ReportViewer(PS:需要安装Microsoft SQL Server System CLR T ...

  3. unfortunately launcher has stopped

    设定虚拟机的配置.

  4. 如何hash一条有向边

    之前这个问题还困扰了我好久,但是现在我才明白这个很蠢的问题 那就是(3,7)(4,9)(3,3)这种有向序点对(括号可能用的不对) 我们可以变成对"(3,7)"字符串的hash,当 ...

  5. jq中.prop()与attr()的区别

    一,定义 prop() 方法设置或返回被选元素的属性和值.prop() 方法应该用于检索属性值 attr()  方法设置或返回被选元素的属性和值.如需检索 HTML 属性,请使用 attr() 方法代 ...

  6. 【转】最近搞Hadoop集群迁移踩的坑杂记

    http://ju.outofmemory.cn/entry/237491 Overview 最近一段时间都在搞集群迁移.最早公司的hadoop数据集群实在阿里云上的,机器不多,大概4台的样子,据说每 ...

  7. JMeter中的场景执行持续时间设置

    jmeter之调度器配置 JMeter的线程组设置里有一个调配器设置,用于设置该线程组下脚本执行的开始时间.结束时间.持续时间及启动延迟时间.当需要半夜执行性能测试时会用到这个功能. 设置调度器配置, ...

  8. hdu 5446 Unknown Treasure Lucas定理+中国剩余定理

    Unknown Treasure Time Limit: 1500/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Other ...

  9. unicode-range 字体混搭(转)

    最先想到的方法是定义两个拥有不同字体CSS类分别赋予不同的元素. <div class="font1"></div> <div class=" ...

  10. 基于netty的微服务架构

    基于netty的微服务架构 微服务一篇好文章 http://san-yun.iteye.com/blog/1693759 教程 http://udn.yyuap.com/doc/essential-n ...