【发布时间】:2019-10-28 12:59:39
【问题描述】:
这是我第一次使用 API,我使用 httpClient.getAsync(uri) 来获取 CSV 格式的响应。 。
我想知道如何修剪或删除部分内容以获取某些值。我试过用';'分割它但是有太多的混乱,到目前为止我所尝试的都没有奏效。我试图在这里获得的 4 个值是 65.7、45.3、64.4、111.1,它们都位于其中 2 个“;”之间在文件的中间。以 CSV 文件的形式,它将是我想要的第 3 列 (0-3)。
httpClient.BaseAddress = new Uri("https://opendata-download-metobs.smhi.se/api.json");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (HttpResponseMessage response = await httpClient.GetAsync(new Uri("https://opendata-download-metobs.smhi.se/api/version/latest/parameter/23/station/53430/period/latest-months/data.csv")))
{
res = MakeReadable(response);
Console.WriteLine(res);
noteMessage(ConsoleColor.Red, "Csv Processing");
string s = res.Substring(res.LastIndexOf("Från"));
Console.WriteLine(res);
Console.WriteLine(
response.IsSuccessStatusCode
? "Verification successful"
: $"Verification failure: {response.ReasonPhrase}");
}
}
MakeReadable 看起来像这样:
public static string MakeReadable(HttpResponseMessage apiResponse)
{
string temp = "";
HttpContent responseContent = apiResponse.Content;
Task<string> results = responseContent.ReadAsStringAsync();
temp = results.Result;
return temp;
}
我不明白要使用什么方法。我尝试使用 .Remove() 开始和结束,但它什么也没做。我已经尝试清理除数字之外的所有内容,但最终我得到了很多数字,这也让我失望了。在上面的代码中,我什至尝试 Substring + LastIndexOf 只是为了删除字符串中不必要的部分,但没有任何效果。
【问题讨论】:
-
有很多资源可以读取 CSV 文件并定位特定的列和字段。你看过吗?不要重新发明轮子。
-
听起来您正在将拆分功能应用于整个文件。第一步是将文件拆分为单独的行。然后遍历行并由 ; 分割。分隔器。这样您就可以通过索引轻松访问特定的列值。
-
Check 出这个,确实有帮助。
-
不相关:
Task<string> results = responseContent.ReadAsStringAsync(); temp = results.Result;- 没有,一直异步。