如何仅在C#字符串中存储“

时间:2019-03-06 14:36:24

标签: c# json

我想从字符串中获取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,这是因为字符串中的\“而不是”。我该如何解决?

1 个答案:

答案 0 :(得分:3)

您可以将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;
    }
}