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. OpenMesh 读写网格控制(读取写入纹理坐标,法向等)

    OpenMesh读取网格默认是不自动读取obj网格中的法向,纹理坐标等信息的,写入网格同样也是.所以要读取(或写入)这些信息需要修改默认的选项. 先看一下其读写网格的函数 template<cl ...

  2. java 请求 google translate

    // */ // ]]> java 请求 google translate Table of Contents 1. 使用Java获取Google Translate结果 1.1. 开发环境设置 ...

  3. How Kafka’s Storage Internals Work

    In this post I'm going to help you understand how Kafka stores its data. I've found understanding th ...

  4. SQL多表查询案例

    表结构: emp表: dept表: salgrade表: (1)查出至少有一个员工的部门.显示部门编号.部门名称.部门位置.部门人数. SELECT z.*,d.dname,d.loc FROM de ...

  5. hive中大表join

    排序存储数据至BUCKETS,这样可以顺序进行join

  6. JavaScript设计模式——单体模式

    一:单体模式简介: 是什么:将代码组织为一个逻辑单元,这个单元中的代码通过单一的变量进行访问.只要单体对象存在一份实例,就可以确信自己的所有代码使用的是同样的全局资源. 用途:1.用来划分命名空间,减 ...

  7. js整理1

    数组 比较时的隐式转化 var a = [1,2,3]; var b = [1,2,3]; a == b; //false a == '1,2,3'; //true; // var c = []; B ...

  8. delphi 对Tmemo指定的行写入

    mmoMonitor:Tmemo; mmoMonitor.Lines.ValueFromIndex[0]:=aInfo ; procedure TMainForm.LogInfo(aInfo: str ...

  9. js小例子(多字溢出,省略号表示)

    实现了div中字数较多,显示不下的时候,用省略号来表示,并且可以展开和收起: <html> <head> <meta http-equiv="Content-T ...

  10. Codeforces Round #345 (Div. 2)

    DFS A - Joysticks 嫌麻烦直接DFS暴搜吧,有坑点是当前电量<=1就不能再掉电,直接结束. #include <bits/stdc++.h> typedef long ...