如何发出GET请求并将结果解析为列表

时间:2015-09-27 15:59:12

标签: c# asp.net asp.net-mvc parsing filehelpers

数据包含place_id和其他列:

place_id    name    city    address ..
133 place1  Laagri  Born 12 ..
161 place2  Mourdi  Karve 12  ..

可提供5种不同格式的数据。所有这些网址都返回相同的数据:

http://www.smartpost.ee/places.html
http://www.smartpost.ee/places.xml
http://www.smartpost.ee/places.csv
http://www.smartpost.ee/places.js
http://www.smartpost.ee/places.php

应选择其中一个网址来获取数据。数据可能会更改,因此不应缓存。 如何发出http GET requet并创建两个元素List:第一个元素是第一列的place_id,第二个元素是连接的名称,城市和地址字段。类似的东西:

class DeliveryList {
   public string Id, Address;
  }

List<DeliveryList> res= GetAndParse("http://www.smartpost.ee/places.csv", 
    "place_id, name+\" \"+ city +\" \" + address" );

如何实施GetAndParse?应该将http请求保存到sting和用于解析它的文件管理器吗?表达式"place_id, name+\" \"+ city +\" \" + address"可以在代码中进行硬编码,而不是作为参数传递。

使用ASP.NET MVC4,.NET 4,C#。代码应该在服务器中的MVC4控制器中运行。

2 个答案:

答案 0 :(得分:2)

我建议你使用XML端点并对下面实现的地方数组实现反序列化:

public static class PlacesHelper
{
    private const string EndpointUrl = "http://www.smartpost.ee/places.xml";

    /// <summary> Load array of places </summary>
    public static async Task<Places> LoadPlacesAsync()
    {
        var xmlString = await HttpRequestHelper.DownloadStringAsync(EndpointUrl);
        return SerializationHelper.DeserializeXmlString<Places>(xmlString);
    }
}

public static class SerializationHelper
{
    /// <summary> Deserializes Xml string of type T. </summary>
    public static T DeserializeXmlString<T>(string xmlString)
    {
        T tempObject = default(T);

        using (var memoryStream = new MemoryStream(StringToUTF8ByteArray(xmlString)))
        {
            var xs = new XmlSerializer(typeof (T));
            var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

            tempObject = (T) xs.Deserialize(memoryStream);
        }

        return tempObject;
    }

    /// <summary> Convert String to Array </summary>
    private static Byte[] StringToUTF8ByteArray(String xmlString)
    {
        return new UTF8Encoding().GetBytes(xmlString);
    }
}

public static class HttpRequestHelper
{
    /// <summary> Download String Async </summary>
    public static async Task<string> DownloadStringAsync(string uri)
    {
        var client = new WebClient();
        return await client.DownloadStringTaskAsync(uri);
    }
}

[Serializable]
[XmlRoot("places_info", Namespace = "")]
public class Places
{
    [XmlElement("place", typeof(Place), Form = XmlSchemaForm.Unqualified, IsNullable = false)]
    public Place[] Place { get; set; }
}

[Serializable]
public class Place
{
    [XmlElement("place_id")]
    public string Id { get; set; }

    [XmlElement("name")]
    public string Name { get; set; }

    [XmlElement("city")]
    public string City { get; set; }

    [XmlElement("address")]
    public string Address { get; set; }
}

用法:

var arrayOfPlaces = await PlacesHelper.LoadPlacesAsync();

因此,您将获得一系列地点(身份证,姓名,城市,地址)。

<强>更新

对于.NET Framework 4,Microsoft发布了Async Targeting Pack (Microsoft.Bcl.Async)Nuget。所以安装软件包&#39; Microsoft Async&#39;来自Nuget,您将能够使用async / await。

控制器操作的示例实现:

public class TestController : Controller
{
    public async Task<object> GetPlaces()
    {
        return Json(await PlacesHelper.LoadPlacesAsync(), JsonRequestBehavior.AllowGet);
    }
}

答案 1 :(得分:1)

我使用XmlSerializer选择XML格式来解析数据。这是代码。

类代表我们的XML数据:代码是自我解释的

[XmlRoot("places_info")]
public class PlacesInfo
{
    [XmlElement("place")]
    public Place[] Places { get; set; }
}

public class Place
{
    [XmlElement("place_id")]
    public string Id { get; set; }

    [XmlElement("name")]
    public string Name { get; set; }

    [XmlElement("city")]
    public string City { get; set; }

    [XmlElement("address")]
    public string Address { get; set; }
}

您的Delivery班级:

public class Delivery
{
    public string Id { get; set; }
    public string Address { get; set; }

    public Delivery(string id, string address)
    {
        Id = id;
        Address = address;
    }
}

获取和解析数据的代码:

static void Main(string[] args)
{
    // Get XML string from web
    var client = new WebClient();

    // Set encoding for non-ASCII characters
    client.Encoding = Encoding.UTF8;

    string xml = client.DownloadString("http://www.smartpost.ee/places.xml");

    // Create a serializer
    var serializer = new XmlSerializer(typeof(PlacesInfo));

    // Variable to hold all XML data
    PlacesInfo info;

    // Deserialize XML string to object
    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        info = (PlacesInfo) serializer.Deserialize(stream);
    }

    // Create delivery list
    var deliveryList = new List<Delivery>();

    // For each place
    foreach (var place in info.Places)
    {
        // Concatenate name, city, and address
        string address = string.Format("{0} {1} {2}", place.Name, place.City, place.Address);

        // Add new delivery
        var delivery = new Delivery(place.Id, address);
        deliveryList.Add(delivery);

        // Display to test
        Console.WriteLine(delivery.Id + " " + delivery.Address);
    }

    Console.ReadLine();
}

我在代码中仔细评论。如果您发现难以理解的内容,请随时告诉我。希望这有帮助:)