I don't really know how to ask this but basically,
I have a url http://URL.com/filename.json
and I would like to fetch the data from /filename.json and "convert it to text".
The url file contains the following: {"CurrentVersion": "1.0"}
and I would like to get the CurrentVersion and define a string with its value (1.0).
One possibility is to make use of System.Net.WebClient for downloading the data: (Outdated, see Edit below.)
// WebClient is outdated
string json;
using(var webClient = new WebClient())
{
json = webClient.DownloadString("http://URL.com/filename.json");
}
after downloading the string you can deserialize it with a framework like Json.Net. Because it is a simple JSON file we can deserialize it into a dictionary. This way we do not have to create an explicit class for it:
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
Now we can access the version like this:
var versionString = dict["CurrentVersion"];
Edit
Like #CodeCaster stated in the comments: The usage of System.Net.WebClient is outdated. Instead one should use System.Net.Http.HttpClient. Downloading the JSON could then look something like this:
// HttpClient is intended to be instantiated once per application, rather than per-use.
private readonly HttpClient _httpClient = new HttpClient();
[...]
var json = _httpClient.GetStringAsync("http://URL.com/filename.json");
// Do something with JSON
Related
This question already has answers here:
Read Json Serialized c#
(2 answers)
Closed 3 years ago.
I wanted to be able to access my data from anywhere so I made a c# data API that returns json for gets and accepts json for posts. All methods use HTTPResponseMessage as a return type so that I can send back the appropriate responses.
In jquery ajax its a simple thing to use and it works great but when I try to use c# mvc I am completely lost where and how to get the data returned from my API into the data model.
I tried using this in my viewModel. It got the data but then what
static public object GetProfile()
{
string url = "http://localhost:50121/api/Profile/1";
var client = new WebClient();
var content = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var jsonContent = serializer.Deserialize<object>(content);
return jsonContent;
}
public readonly object d = GetProfile();
Sorry if I am posting this wrong I have not asked questions here a lot.
I just want to populate my model with the json returned from the api call.
This line:
var jsonContent = serializer.Deserialize<object>(content);
Should be changed to:
var jsonContent = serializer.Deserialize<YourModelClass>(content);
Where YourModelClass is the model that you want to deserialise into.
Deserialize json straight to your model class (ModelClass in this example since you did not provide your model class definition).
using Newtonsoft.Json;
static public ModelClass GetProfile()
{
string url = "http://localhost:50121/api/Profile/1";
var client = new WebClient();
//object serialised as json string
var content = client.DownloadString(url);
//object deserialised as ModelClass
var model = JsonConvert.DeserializeObject<ModelClass>(json);
return model;
}
I have a c# object: a list with objects (objects have ID and Name)
Now I need to include the list of objects (it should be json string as far as I understand) in URL as parameter. How is it possible to do it?
If I understand you correctly, you need this.
var client = new WebClient();
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
string response = client.UploadString("http://mysite", "json string");
I am looking for a way to access the serialized result of the AddBody call.
I am using the built in RestSharp Serializer.
Example:
class Foo
{
public string FooField;
}
void SendRecord()
{
var f = new Foo();
f.FooField = "My Value";
request.AddBody(f);
// How do I get the serialized json result of the add body call without
// data? I would like to log the serialized output of the add body call to
// the database.
//Expected {"FooField":"My Value"}
var response = client.Execute(request);
}
I figured it out by finding this post.
request.Parameters.Where(p => p.Type == ParameterType.RequestBody).FirstOrDefault();
I also struggled with this (using v107 preview) and couldn't find any examples of logging the actual string sent to the server. The issue I was trying to debug was getting the right serialisation settings so the object was no use to me.
The only way I could find to get the serialized body as a string was to hook into the OnBeforeRequest event on the RestRequest:
var request = new RestRequest("/", Method.Post)
.AddHeader(KnownHeaders.ContentType, "application/json", false)
.AddJsonBody(myObj);
request.OnBeforeRequest = async (httpRequest) =>
{
var requestBodyStr = await httpRequest.Content.ReadAsStringAsync();
Trace.WriteLine($"Request body: {requestBodyStr}");
};
RestSharp itself doesn't expose the serialized request body when you pass an object to it.
There is a way to get at it though, I just posted over here:
https://stackoverflow.com/a/75537611/2509281
Right off the RestSharp homepage (http://restsharp.org/):
// execute the request
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string <~~~~~~~~~~
I am working in calling PHP API from c#. But, my problem arise when I have to pass associative array to API. I don't know exact implementation of PHP associative array in C# but I have used dictionary. It didn't works.
I have been using RestSharp to call API.
Code Implemenation:
var client = new RestClient(BaseUrl);
var request = new RestRequest(ResourceUrl, Method.POST);
IDictionary<string,string> dicRequeset = new Dictionary<string, string>
{
{"request-id", "1234"},
{"hardware-id", "CCCCXXX"},
};
request.AddParameter("request", dicRequeset);
var response = client.Execute(request);
var content = response.Content;
PHP API Implementation(Short):
* Expected input:
* string request[request-id,hardware-id]
* Return:
* code = 0 for success
* string activation_code
*/
function activate()
{
$license = $this->checkFetchLicense();
if (!$license instanceof License) return;
$response = $license->activate((array)$this->_request->getParam('request'));
}
Can someone help me to pass array to PHP API from C#?
Maybe adding the pairs makes differences in conventions in C# and PHP? Have you tried using Add?
IDictionary<string,string> dicRequeset = new Dictionary<string, string>();
dicRequeset.Add("request-id", "1234");
dicRequeset.Add("hardware-id", "CCCCXXX");
Or using indexer?
dicRequeset["request-id"] = "1234";
dicRequeset["hardware-id"] = "CCCXXX";
Or the best I can imagine is JSON as it is designed for the purpose of transmission.
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new {request-id = "1234", hardware-id = "CCCXXX"});
The problem in the third variant despite I marked it as the best, might be that the PHP API may not decode the JSON string, because it might not be designed that way. But in general purpose JSON is meant to solve that kind of problems.
Though late post but I've solved this problem by using following approach :
var request = new RestRequest(ResourceUrl, Method.POST);
request.AddParameter("request[request-id]", hardwareId);
request.AddParameter("request[hardware-id]", hardwareId);
if I guess right, the AddParameter method of RestSharp doesn't automatically serialize an object to json thus insteadly just calls the object's toString method.
So try to get a JSON.net library and make the json encoding manually,
IDictionary<string,string> dicRequeset = new Dictionary<string, string>
{
{"request-id", "1234"},
{"hardware-id", "CCCCXXX"},
};
var jsonstr = JsonConvert.SerializeObject(dicRequeset);
request.AddParameter("request", jsonstr);
this should work.
I am trying to use a HTTP request to return the contents of a json string from google shopping api. What I have so far seems to be working but I would like to know how I can use the contents of the object to display the data on a page.
public string HttpGet(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
try
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
return reader.ReadToEnd();
}
}
finally
{
response.Close();
}
}
protected void submit_Click(object sender, EventArgs e)
{
string json = HttpGet("https://www.googleapis.com/shopping/search/v1/public/products?key={KEY}4&country=UK&q=BX80637153570K&rankBy=price:ascending&maxResults=1&alt=json");
dynamic obj = JsonObject.Parse(json);
}
Ok looking at the responses it looks as though I need a C# class for the data returned in json. I have created a classes using json2csharp.com. This is the data I need to return from the Json and display on the page. Maybe it will help explain my problem better.
https://www.googleapis.com/shopping/search/v1/public/products?key=AIzaSyCC0j59RBeGNtf2W2ft6avhfoTdJ1FQ2c4&country=UK&q=BX80637153570K&rankBy=price:ascending&maxResults=1&alt=json
Can anyone advise how I can use this information on my website. I am a little lost now as I'm new to all this and have tried several different methods.I don't need all of the returned data if that makes a difference? Just price and link.
Supposing dynamic obj is rightly filled you can use it's content in web page
For examples, if json is:
{
"error" : {
"code": 400,
"message": "Bad Request"
}
}
You can access object properties with code like this:
Response.Write("Error code is" + obj.error.code);
Of course Response.Write is only a sample on how you can send retrieved data to the page.
Edit 1:
It seems json converter used in question is not working or not working right.
In many cases, it's overkill to create a concrete class only to parse a json, expecially since C# 4 that can use ExpandoObject
This is a sample on how you can deserialize in a dynamic object without the need to create a concrete object
var url = "http://www.google.com/ig/calculator?hl=en&q=100USD=?EUR";
string json = HttpGet(url);
//this is json string:
//{lhs: "100 U.S. dollars",rhs: "78.1799703 Euros",error: "",icc: true}
//now convert in a dynamic object
var jss = new DynamicJsonConverter();
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic obj = serializer.Deserialize(json, typeof(object));
//now you have access to json content
string text1 = obj.lhs;
string text2 = obj.rhs;
DynamicJsonConverter class can be created using code you can find here:
Deserialize JSON into C# dynamic object?
I think you need to deserialize the response
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
You will need to create a class with the property resulted by the response.
Say test class
class Test
{
//define a similar property here
// which you suppose it will be return in the response
}
Then
Test routes_list = (Test)json_serializer.DeserializeObject(yourjson);
Edit 1
Or you can go through this link
How to Convert JSON object to Custom C# object?