Easiest way to read from a response from URL - c#

I am new to C#, and did not find an easy piece of code to read a response from a URL. Example:
http://www.somesitehere.com/mysearch
The response is something like this ( I do not know what kind of response is this):
{ "response": {
"status": {
"code": "0",
"message": "Success",
"version": "4.2"
},
"start": 0,
"total": 121,
"images": [
{
"url": "www.someimagelinkhere.com/pic.jpg",
"license": {
"url": "",
"attribution": "",
"type": "unknown"
}
}
]
}}
After that I will to save that url "www.someimagelinkhere.com/pic.jpg" to a file. But this I know how to do. I just want to separate the url from the rest.
I saw this topic: Easiest way to read from a URL into a string in .NET
bye

Your response is of JSON Format. Use a library (NewtonSoft but there are others too) to extract the node you want.

You can use something like JSON.NET by Newton soft, which can be found and installed using NuGet Package Manager in Visual Studio.
Also you could just do this.
var jSerializer = new JavaScriptSerializer();
var result = jSerializer.DeserializeObject("YOUR JSON RESPONSE STRING");
The JSON string will not be a C# object with properties that match your names such as start, total, images, etc. If you need to you can create a strong type object and cast your converted object to that one for ease of use.
Strong typed version:
var jSerializer = new JavaScriptSerializer();
var result = (YourStrongType)jSerializer.DeserializeObject("YOUR JSON RESPONSE STRING");
var imgUrl = result.images[0].url;

Related

How do you deserialize a JSON to get a string value without having to build an entire model? Below is example code I included

Example JSON, for example say I want the quote and author values. I wasn't able to get them unless I built a model around the JSON, which I'm not wanted to do as it would be more time consuming.
{
"success": {
"total": 1
},
"contents": {
"quotes": [
{
"quote": "Plant your own garden and decorate your own soul, instead of waiting for someone to bring you flowers.",
"length": "102",
"author": "Veronica A. Shoffstall",
"tags": [
"flowers",
"inspire",
"self-help",
"soul"
],
"category": "inspire",
"language": "en",
"date": "2022-12-22",
"permalink": "https://theysaidso.com/quote/veronica-a-shoffstall-plant-your-own-garden-and-decorate-your-own-soul-instead-o",
"id": "LQbKQGxVA2rcH4lIwn6OIweF",
"background": "https://theysaidso.com/img/qod/qod-inspire.jpg",
"title": "Inspiring Quote of the day"
}
]
},
"baseurl": "https://theysaidso.com",
"copyright": {
"year": 2024,
"url": "https://theysaidso.com"
}
}
My test example code with URL below. I tried it with Dynamic Object but can never get to the string.
try
{
private static readonly HttpClient _httpClient = new HttpClient();
// Make the API request
var response = _httpClient.GetAsync("https://quotes.rest/qod?language=en").Result;
response.EnsureSuccessStatusCode();
// Do something with the response
var value11 = response.Content.ReadAsStringAsync().Result;
var gett = JsonConvert.DeserializeObject<dynamic>(value11);
var quote= gett.contents.quotes.quote;
return quote;
}
catch (Exception ex)
{
quote = ex.Message;
return quote;
}
Looking at the JSON structure the quotes property is an array and as such you should use
var quote = gett.contents.quotes[0].quote;
Assuming that deserialization was not the cause of the failure.
There is no json convert error. quotes is array you can access gett .contents.quotes[0].quote.
Tips; you don't need to json convert and ReadAsString you can easily use like response.Content.ReadFromJsonAsync().Result?.contents.quotes[0].quote

Sending a json object in a post method

I am trying to create a virtual machine through a post method but I have not been able to create it since I cannot send the json file correctly.
This is my code:
// Create a json object
var deploy = new Deploy
{
name = "RandomName",
folder = "folder_3044",
resource_pool = "resgroup-4035"
};
//Change it into a json file
var deployResult = JsonConvert.SerializeObject(deploy);
//Change this file into a string so we can send it to the post method
var jsonContent = new StringContent(deployResult);
//Make post and send the needed information
var postResponse = await httpClient.PostAsync("URI", jsonContent);
return (content);
When executing my code in Postman it gives me a false positive because it sends something but it seems that it does not send the json as I wanted but the code below:
{
"headers": [
{
"key": "Content-Type",
"value": [
"text/plain; charset=utf-8"
]
},
{
"key": "Content-Length",
"value": [
"97"
]
}
]
}
Can anyone help me with this? I just need to send that json in my post like I do when sending from Postman.
Ps: I use .Net core and I can't change even if I want to.
This is the json that should be sent for it to work:
{
"name": "RandomName",
"placement": {
"folder": "folder_3044",
"resource_pool": "resgroup-4035"
}
}
Thank you to #Peter Csala's comment: When I specified the content-type as you advised, it worked. Just for future references, we need these two lines of code. (Don't forget to include the assembly System.Text on top.)
using System.Text;
new StringContent(deployResult, Encoding.UTF8, "application/json");

Deserializing JSON from webpages - Always the wrong Syntax?

I'm trying to scrape pages, find their schema.org script, then deserialize it.
I am able to find the script, however, valid JSON schema (according to Google/schema.org) is supposedly invalid in most Json Validator tools.
For example, this is my code
string Url = "https://www.independent.co.uk/news/health/nhs-pay-health-coronavirus-unions-b1812659.html";
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(Url);
var scripts = doc.DocumentNode.SelectNodes("//script");
foreach (HtmlNode node in scripts)
{
string value = node.InnerText;
if (value.Contains("schema.org"))
{
dynamic results = JsonConvert.DeserializeObject<dynamic>(value);
var name = results.name;
}
}
Which finds the following Schema (JSON)
{{
"#type": "Organization",
"#context": "https://schema.org",
"name": "The Independent",
"url": "https://www.independent.co.uk",
"logo": {
"#type": "ImageObject",
"url": "https://www.independent.co.uk/img/logo.png",
"width": 504,
"height": 60
},
"sameAs": [
"https://twitter.com/Independent",
"https://www.facebook.com/TheIndependentOnline"
]
}}
#1 The JSON is supposedly invalid, even though every website using structured data uses it like this
#2 When I try to get the name value, it returns null.
I assume my problems are because the JSON is invalid. How do I make this work? I'm out of ideas.
You need to get rid of the extra curly brackets at the start and end of the JSON to make it valid JSON.

Format JSON response using ASP.NET JsonResult Class

I'm trying to integrate BlueImp jQuery file upload component into my ASP.NET 4 website. I have the file upload working and writing to disk, but the component requires that I return a JSON object from the server as confirmation of success, in a particular format:
{"files": [
{
"name": "picture1.jpg",
"size": 902604,
"url": "http:\/\/example.org\/files\/picture1.jpg",
"thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
"deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
"deleteType": "DELETE"
},
{
"name": "picture2.jpg",
"size": 841946,
"url": "http:\/\/example.org\/files\/picture2.jpg",
"thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture2.jpg",
"deleteUrl": "http:\/\/example.org\/files\/picture2.jpg",
"deleteType": "DELETE"
}
]}
I'd like to use the JsonResultClass to return this object in my C#, but I'm not sure how to format the response correctly. I can probably do something like this:
var uploadedFiles = new List<object>();
uploadedFiles.Add(new { name = "picture1.jpg", size = 902604, url = "http://example.org/files/picture1.jpg", thumbnailUrl = "http://example.org/files/thumbnail/picture1.jpg", deleteUrl ="http://example.org/files/picture1.jpg", deleteType = "DELETE" });
uploadedFiles.Add(new { name = "picture2.jpg", size = 902604, url = "http://example.org/files/picture1.jpg", thumbnailUrl = "http://example.org/files/thumbnail/picture1.jpg", deleteUrl ="http://example.org/files/picture1.jpg", deleteType = "DELETE" });
return Json(uploadedFiles);
...but then I'm not sure how to wrap this in the outer 'files' object.
Can anyone point me (a .NET novice trying to learn!) in the right direction here. I've looked at the MSDN documentation but it doesn't go into detail about formatting or constructing more complex JSON objects.
Many thanks.
Replace:
return Json(uploadedFiles);
with:
return Json(new {files = uploadedFiles});
to create a new anonymous type with property "files", which has your original list as a value.

Retrieving "images" from a JSON string retrived from Instagram API

Using C# and Visual Studio 2010 (Windows Form Project), InstaSharp and Newtonsoft.Json libraries.
I want to get the image url from the JSON string returned to me by the Endpoint Instagram API when I request for a particular hashtag.
I can so far retrive the JSON string.
I am trying to use Newtonsoft.Json to deserialize the object using the examples, but I probably dont understand the JSON string representation of the object properly.
Below is a simplified sample response I get from the api call tags/tag-name/media/recent from their documentation. source here
{
"data": [{
"type": "image",
"filter": "Earlybird",
"tags": ["snow"],
"comments": {
}
"caption": {
},
"likes": {
},
"created_time": "1296703536",
"images": {
"low_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_7.jpg",
"width": 612,
"height": 612
}
},
"id": "22699663",
"location": null
},
...
]
}
I want to get specifically the standard_resolution in the images part.
This is the revelevant code that I currently have.
//Create the Client Configuration object using Instasharp
var config = new InstaSharp.Endpoints.Tags.Unauthenticated(config);
//Get the recent pictures of a particular hashtag (tagName)
var pictures = config.Recent(tagName);
//Deserialize the object to get the "images" part
var pictureResultObject = JsonConvert.DeserializeObject<dynamic>(pictureResult.Json);
consoleTextBox.Text = pictureResult.Json;
var imageUrl = pictureResultObject.Data.Images;
Console.WriteLine(imageUrl);
I get the error: Additional information: Cannot perform runtime binding on a null reference
so imageUrl is indeed null when I debug, hence indicating I am not accessing it the right way.
Anyone can explain to me how to access different parts of this JSON String using Newtonsoft.Json?
Using Newtonsoft.Json
dynamic dyn = JsonConvert.DeserializeObject(json);
foreach (var data in dyn.data)
{
Console.WriteLine("{0} - {1}",
data.filter,
data.images.standard_resolution.url);
}
I wrote a plugin for .net which takes care of deserializing the json string and returning a data table. it is still in development but see if it helps. Instagram.NET on Github

Categories