WebClient.DownloadData () возвращает Json с html тегами, такими как <pre>из WebApi - PullRequest
0 голосов
/ 22 марта 2020

Я пытаюсь прочитать из нашего производственного API, который всегда выводит json, окруженный

tags <br>
The problem I am facing that when i use WebClient.DownloadData() it don't scrape the json only but also the <pre> tags which is unwanted <br>
I managed to come up with an api that outputs the json in <pre> tags when i try to read from it actually scrape only the json
Here is the working api <a href="https://pokeapi.co/api/v2/pokemon/pikachu/" rel="nofollow noreferrer">https://pokeapi.co/api/v2/pokemon/pikachu/</a> <br>
I tried to copy the formatting in the production api but no use</p>

<pre><code>String Json = System.Text.Encoding.UTF8.GetString((byte[])(new System.Net.WebClient().DownloadData("https://pokeapi.co/api/v2/pokemon/pikachu/")));
Console.WriteLine(Json);
Json = System.Text.Encoding.UTF8.GetString((byte[])(new System.Net.WebClient().DownloadData("remote-api-url")));
Console.WriteLine(Json);
</code>

Почему

tags does appear in the first print only and the sources of the two documents has those <pre> tags</p>

<h2>Update:</h2>

<p>It turned out that i use <strong>ContentResult</strong> to return put my json along with <pre> tags on the page so when i use this approach i get to output json with using the Formmatting.Indented .. Here is the code</p>

<pre><code>return Content("<pre style =\"word-wrap: break-word; white-space: pre-wrap;\">" +new Response() { Status = "Success", Payload = null }.ToJsonString(Formatting.Indented)+ "
");

благодаря Замечание rene об источнике страницы, я знал следующее: при использовании ContentResult источник страницы генерируется как полный html документ в отличие от JsonResult , который будет выведите источник, содержащий только json, и он сгенерирует

tags automatically here is the code</p>

<pre><code>return Json(new Response() { Status = "Success", Payload = null },JsonBehaviour.AllowGet);
</code>

Что, если я хотел бы иметь мой json с отступом? тогда подход ContentResult должен использоваться в API вместе с Ответ Дэвида , чтобы избавиться от тегов

в агенте. 
< >

1 Ответ

1 голос
/ 22 марта 2020

Просто обработайте ответ как XML и извлеките значение узла root.

например

<code>            var xml = @"
<pre style =""word - wrap: break-word; white - space:
pre - wrap; "">{""Status"":""Success"",""Payload"":null}
"; var json = XDocument.Parse (xml) . Root. Значение;
...