0

I'm creating a GUI in Visual Studio which is going to fetch JSON data from an API to display in a text box, and I want it to be displayed formatted so it's readable.

I have tried to use the Newtonsoft.Json library to solve the problem, but it seems like it does not work on one liners of JSON and must take an object containing different types of JSON data.

using (WebClient wc = new WebClient())
{
    string API_Key = "000000000000000000000"; // URL with API key containing the JSON data

    string JSON_Data_URL = $"https://www.nobil.no/api/server/datadump.php?apikey={API_Key}&countrycode=NOR&fromdate=2005-01-01&format=json";
    LoadJSON.Increment(-100); // Reset loadbar
    string JSON_Data = JsonConvert.SerializeObject(wc.DownloadString(JSON_Data_URL), Formatting.Indented); // Format JSON data

    DataResults.Text = JSON_Data; // Add JSON data to textbox
    LoadJSON.Increment(100); // Display when the JSON data is fetched
}

I thought it would output an formatted JSON string, but seems like it instead is just adding backslashes to the JSON. I also tried to replace the backslashes with a new line and 4 spaces, but that didn't look right either.

Edit

This is not a duplicate as the problem seemed to be that I needed to convert the string to an object.

0

1 Answer 1

4

The problem is, that you are serializing a string and not an object.

string JSON_Data = "..." // Get your json from your API
object JSON_Object = JsonConvert.DeserializeObject(JSON_Data);
string JSON_Data_Formatted = JsonConvert.SerializeObject(JSON_Object, Formatting.Indented);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.