我想从字符串中获取 JSON,我需要在我的代码中提取“而不是\”。

这是我想在其中使用它的代码:

internal static string ReturnRedditJsonPage(string subredditname)
{
    return
    $"https://reddit.com/r/{subredditname}.json";
}
internal static Reddit ParseReddit(string subredditname)
{
    WebResponse response = HttpWebRequest.CreateHttp(ReturnRedditJsonPage(subredditname)).GetResponse();
    string responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd().Replace("\\",@"\").Replace("\"",((char)0x0022).ToString()).Trim();
    return JsonConvert.DeserializeObject<Reddit>(responseContent);
}
internal static Uri[] GetMemesLinks(string subredditname)
{
    Reddit jsonData = ParseReddit(subredditname);
    List<Uri> result = new List<Uri>();
    foreach(Child child in jsonData.Data.Children)
    {
        result.Add(child.Data.Url);
    }
    return result.ToArray();
}

它给我返回 JSON,因为字符串中的\"而不是 ".我该如何解决?

最佳答案

您可以使用 JSON.NET 加上一点 LINQ 魔法从 sub-reddit API 中提取所有 URI。

这是一个演示,根据您的要求进行调整:

internal static string ReturnRedditJsonURI(string SubRedditName)
{
    return $"https://reddit.com/r/{SubRedditName}.json";
}

// Does a HTTP GET request to the external Reddit API to get contents and de-serialize it
internal static async Task<JObject> ParseReddit(string SubRedditName)
{
       string exampleURI = ReturnRedditJsonURI(SubRedditName);

       JObject response = new JObject();
       using (HttpClient client = new HttpClient())
       {
            // Make the HTTP request now
            HttpResponseMessage msg = await client.GetAsync(exampleURI);

            // If HTTP 200 then go ahead and de-serialize
            if (msg.IsSuccessStatusCode)
            {
                string responseBody = await msg.Content.ReadAsStringAsync();
                response = JsonConvert.DeserializeObject<JObject>(responseBody);
            }
       }
       return response;
}

// Driver method to extract the URI(s) out of the reddit response
internal static async Task<List<Uri>> GetRedditURI(string SubRedditName)
{
    string subRedditName = "Metallica";
    JObject redditData = await ParseReddit(SubRedditName);

    List<Uri> redditURIList = new List<Uri>();

    try
    {
        // TODO: instead of JObject use concrete POCO, but for now this seems to be it.

        redditURIList = redditData["data"]?["children"]?
            .Select(x => x["data"])
            .SelectMany(x => x)
            .Cast<JProperty>()
            .Where(x => x.Name == "url")
            .Select(x => x.Value.ToString())
            .Select(x => new Uri(x, UriKind.Absolute)).ToList() ?? new List<Uri>();

        return redditURIList;
    }
    catch (Exception ex)
    {
        return redditURIList;
    }
}

关于c# - 如何仅在 C# 字符串中存储 ",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55025607/

10-13 03:24