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 ...
随机推荐
- 遍历进程活动链表(ActiveProcessLinks)、DKOM隐藏进程
1.EPROCESS结构体 EPROCESS块来表示.EPROCESS块中不仅包含了进程相关了很多信息,还有很多指向其他相关结构数据结构的指针.例如每一个进程里面都至少有一个ETHREAD块表示的线程 ...
- github 使用网址
[Github教程]史上最全github使用方法:github入门到精通 http://blog.csdn.net/hcbbt/article/details/11651229 githup的使用 h ...
- $(function(){})与window.onload的区别
不太一样window.onload是在页面所有的元素都加载完成后才触发$(function(){})是在页面的dom结构加载完毕后就触发 dom里的内容不一定都已经加载完成比如说一个页面有好多图片 而 ...
- telnet时显示:允许更多到 telnet 服务器的连接。请稍候再试
telnet时显示:允许更多到 telnet 服务器的连接.请稍候再试 解决办法: windows自带telnet服务器默认的最大连接数为2,要想修改该设置,可以在命令行键入tlntadmn c ...
- Handler(消息机制)
Demo演示 //通过Handler事件倒计时的一个操作,并判断状态 public class MainActivity extends AppCompatActivity {private Text ...
- Liferay 6.2 改造系列之二十三:修改Liferay原始主题中"技术支持:Liferay"字样
1.修改主题模板文件,具体位置如下 (1) portal-master\portal-web\docroot\html\themes\_unstyled\templates\portal_normal ...
- PHP入门 - - 06-->HTML的表格标签
表格标签<table> <table>的属性: Align: left, center, right (表格的)位置 Border: ...
- ADB常用的几个命令
1. 查看设备 adb devices 查看当前连接的设备, 连接到计算机的android设备或者模拟器将会列出显示 2. 安装软件 adb install [-r] [-s] <file> ...
- delphi 中TStringList Clear 方法的时候该对象有没有被释放
delphi 中TStringList 通过function AddObject(const S: string; AObject: TObject): Integer; 方法添加了一个对象,请问我在 ...
- Codeforces Round #342 (Div. 2)
贪心 A - Guest From the Past 先买塑料和先买玻璃两者取最大值 #include <bits/stdc++.h> typedef long long ll; int ...