How parse REST service JSON response
1. get JSON responses and go to :
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的更多相关文章
- 使用Groovy处理SoapUI中Json response
最近工作中,处理最多的就是xml和json类型response,在SoapUI中request里面直接添加assertion处理json response的话,可以采用以下方式: import gro ...
- JavaScript -- JSON.parse 函数 和 JSON.stringify 函数
JavaScript -- JSON.parse 函数 和 JSON.stringify 函数 1. JSON.parse 函数: 使用 JSON.parse 可将 JSON 字符串转换成对象. &l ...
- 【SoapUI】比较Json response
package direct; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject ...
- datatable fix error–Invalid JSON response
This error is pretty common. Meaning:When loading data by Ajax(ajax|option).DataTables by default, e ...
- [SoapUI] 重载JSONComparator比对JSON Response,忽略小数点后几位,将科学计数法转换为普通数字进行比对,在错误信息中打印当前循环的case number及其他附加信息
重载JSONComparator比对JSON Response,忽略小数点后几位,将科学计数法转换为普通数字进行比对,在错误信息中打印当前循环的case number及其他附加信息 package d ...
- [Backbone] Parse not formatted JSON code
The good Dr. recently had another team implement the server and they slightly messed up the format o ...
- 使用JSON.parse()转化成json对象需要注意的地方
http://blog.csdn.net/u011277123/article/details/53055479 有三种方法: var str = '{"name":"小 ...
- [SoapUI] Compare JSON Response(比较jsonobject)
http://jsonassert.skyscreamer.org/ 从这个网站下载jsonassert-1.5.0.jar ,也可以下载到源代码 JSONObject data = getRESTD ...
- [JSON] Validating/Asserting JSON response with Jsonlurper
import groovy.json.JsonSlurper def response = messageExchange.response.responseContent log.info &quo ...
随机推荐
- linux下搭建属于自己的博客(WordPress安装)
转自:http://www.cnblogs.com/xiaofengkang/archive/2011/11/16/2251608.html WordPress简介 WordPress 是一种使用 P ...
- 第四篇:SOUI资源文件组织
什么是资源? 现代的软件只要有UI,基本上少不了资源. 资源是什么?资源就是在程序运行时提供固定的数据源的文件. 在MFC当道的时代,资源一般就是位图(Bitmap),图标(Icon),光标(Curs ...
- C# Thread 线程状态知识
.NET 基础类库的System.Threading命名空间提供了大量的类和接口支持多线程.这个命名空间有很多的类.System.Threading.Thread类是创建并控制线程,设置其优先级并获取 ...
- I/O复用模型之select学习
linux下的I/O模型可以分为5种: 1.阻塞式I/O模型 2.非阻塞式I/O模型 3.I/O复用模型 4.信号驱动I/O模型 5.异步I/O模型 简单解释: 阻塞和非阻塞:就是说需要做一件事的时候 ...
- 简单解释Windows如何使用FS段寄存器
详见附件 jpg改rar
- 智能车学习(十四)——K60单片机GPIO学习
一.头文件: #ifndef __MK60_GPIO_H__ #define __MK60_GPIO_H__ #include "MK60_gpio_cfg.h" /* * 定义管 ...
- OpenGL的消隐与双缓冲
首先是大家可能已经发现,在我们之前提到的所有例子中,在图形的旋转过程中整个图形都有一定程度的闪烁现象,显得图形的过渡极不平滑,这当然不是我们所要的效果,幸好opengl 支 持一个称为双缓存的技术,可 ...
- 【SQL Server】数据库是单个用户的 无法顺利进行操作 怎么解决
1.打开数据库 2.新建查询 ,输入以下的SQL 语句 DECLARE @SQL VARCHAR(MAX); SET @SQL='' SELECT @SQL=@SQL+'; KILL '+RTRIM( ...
- 【转】最近搞Hadoop集群迁移踩的坑杂记
http://ju.outofmemory.cn/entry/237491 Overview 最近一段时间都在搞集群迁移.最早公司的hadoop数据集群实在阿里云上的,机器不多,大概4台的样子,据说每 ...
- git学习 分支特殊处理和配置03
Bug分支: 当在一个分支上工作的时候:突然到其它分支修复bug,当前分支工作还没到要提交的程度:这时候可以使用git stash来将工作分支暂时存储起来: 用git stash list查看stas ...