混乱中从JSON获取数据 [英] Confusion in fetching data from JSON

查看:189
本文介绍了混乱中从JSON获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用的JSON格式返回数据要求一个web服务。现在的实际问题是,我可以在字符串中的特定Web服务URL获取数据。

I am trying to use one web service which returns demanded data in json format. Now the actual point is I can fetch the data from the particular web service url in string.

  string url= @"http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json";

  string jsonString = new WebClient().DownloadString(url);

现在的问题是我得到的字符串中的数据(JSON格式)。但我不知道如何将字符串从这个字符串转换成JSON字符串,以及如何获取数据。

Now the point is I get the data in string (in JSON format). But I dont know how to convert the string into JSON string and how to fetch data from this string.

让我给你举的例子,所以你可以很容易地理解

Let me give you example so you can easily understand

如果我jsonString像

if my jsonString is like

{
   "current":{
      "region":{
         "id":"chicago",
         "name":"Chicago"
      },
      "category":{
         "id":"vehicle",
         "name":"Cars & Vehicles",
         "abbrev":"Vehicles"
      },
      "start":1,
      "num":10
   }
}

如何才能得到REGION_NAME从字符串?希望你理解我!尝试使用<一个href=\"http://api.oodle.com/api/v2/listings?key=TEST&region=chicago&category=vehicle&format=json\"相对=nofollow>测试链接!

推荐答案

添加一个引用到的System.Web,然后添加到您使用一节

Add a reference to System.Web and then add to your using section

using System.Web.Script.Serialization;

然后(使用例如JSON字符串)

Then (using your example json string)

string jsonString = "{\"current\":{\"region\":{\"id\":\"chicago\",\"name\":\"Chicago\"},\"category\":{\"id\":\"vehicle\",\"name\":\"Cars & Vehicles\",\"abbrev\":\"Vehicles\"},\"start\":1, \"num\":10}}";

JavaScriptSerializer serializer = new JavaScriptSerializer();

CurrentRecord currentRecord = serializer.Deserialize<CurrentRecord>(jsonString);

string regionName = currentRecord.current.region.name;

另外添加以下类项目:

Also add the following classes to your project:

[Serializable]
public class CurrentRecord
{
    public current current;
}

[Serializable]
public class current
{
    public region region;
    public category category;
    public int start;
    public int num;
}

[Serializable]
public class region
{
    public string id;
    public string name;
}

[Serializable]
public class category
{
    public string id;
    public string name;
    public string abbrev;
}

这篇关于混乱中从JSON获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆