Store json in variable - c#

I am trying tracking but the json which i get in response is not in correct format. So i want to replace it with something to make it in a correct format.
I want to store returned json data in some string variable. NOTE: I want to store json as it is and I dont want to deserialize it. Is there any way to do so?
This is the tracking link
http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&json_callback=renderExampleThreeResults&lat=30.718263&lon=76.694216

but the json which i get in response is not in correct format. So i want to replace it with something to make it in a correct format
It is jsonp, to get a json response just remove the json_callback=renderExampleThreeResults parameters from the url.
New url is:
http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&lat=30.718263&lon=76.694216

Just save response in string anywhere you want:
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&json_callback=renderExampleThreeResults&lat=30.718263&lon=76.694216");
response.EnsureSuccessStatusCode();
string jsonValue = await response.Content.ReadAsStringAsync();
In jsonValue variable you have json.

Related

Deserializing JSON from RestSharp response

I am receiving a JSON result from this API web page (https://flagrantflop.com/api/endpoint.php?api_key=13b6ca7fa0e3cd29255e044b167b01d7&scope=team_stats&season=2019-2020&season_type=regular&team_name=Atlanta%20Hawks)
Using the RestSharp library, so far I've got this:
var client = new RestClient("https://flagrantflop.com/api/endpoint.php?api_key=13b6ca7fa0e3cd29255e044b167b01d7&scope=team_stats&season=2019-2020&season_type=regular&team_name=");
var request = new RestRequest("Atlanta Hawks", DataFormat.Json);
var response = client.Get(request);
I have tested the URL and the request part that specifies the team and both work.
I know there are a number of methods of deserializing the JSON, however not sure the best way.
The request isn't working because the argument you're supplying in RestRequest is treated as its own page stemming off the base URI.
You can verify that by calling client.BuildUri(request) with your current setup―you'll see that the resolved URL is https://flagrantflop.com/api/Atlanta Hawks, which is why you weren't getting the proper JSON response. I recommend rewriting the request like this, but there are other valid ways:
var client = new RestClient("https://flagrantflop.com/api/")
.AddDefaultQueryParameter("api_key", "13b6ca7fa0e3cd29255e044b167b01d7")
.AddDefaultQueryParameter("scope", "team_stats")
.AddDefaultQueryParameter("season", "2019-2020")
.AddDefaultQueryParameter("season_type", "regular");
var request = new RestRequest("endpoint.php")
.AddQueryParameter("team_name", "Atlanta Hawks");
After that, you can have RestSharp automatically deserialize your response:
RootObject response = client.Get<RootObject>(request);
By default, this uses SimpleJson to deserialize your object.

Json sent by xamarin has no data at end

I am trying to send the following JSON file to the web API I created. But, the API is working fine and sending no data and not taking the data from the sent JSON file. While it is being able to take data from postman sent JSON file.
I have tried using the ToString() method with the JSON object and also tried postman to verify if my API is working fine. The API seems to work properly with postman send JSON file but the file sent by the Xamarin forms is sending no data in the JSON file or something and database get no data in it.
There are no errors being shown but the data is not being uploaded to the database please do help me to get this done faster.
coding is below,
public async void check2(object sender, EventArgs e)
{
var httpClient = new HttpClient();
var post = new poster {user=username.Text, pass=password.Text};
string json = JsonConvert.SerializeObject(post);
var content = new StringContent(json,Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = httpClient.PostAsync("http://licapi.witlyf.com/api/values", content);
App.Current.MainPage = new NavigationPage(new navigator(username.Text));
}
The answer has been met it seems I have put my JSON file variable names to be different than in web API so when I made the same the link worked the data was submitted to the database.

How to capture JSON request message

var response = await client.PostAsJsonAsync("customers/xxxx/xxxxx/documents", requestMessage);
requestMessage is a C# object representation of JSON. When using PostAsJsonAsync, I do not get the same response as posting a JSON string. I want to somehow intercept, may be write to log file or somewhere and check the JSON string that is being constructed for verification.
Please suggest.
I figured it out, its simply by using the serializeobject on JsonConvert
var serializedObject = JsonConvert.SerializeObject(requestMessage);

Deserializing a local xml file using Rest Sharp

I have no problem deserializing an xml into my class while using the following code. I was wondering if it was possible to use the same code on a local file, as our source files are saved locally for archival purposes and are occasionally reprocessed.
This works for remote xml but not for local xml:
RestRequest request = new RestRequest();
var client = new RestClient();
//doesnt work
client.BaseUrl = directory;
request.Resource = file;
//works
client.BaseUrl = baseURL;
request.Resource = url2;
IRestResponse<T> response = client.Execute<T>(request);
return response.Data;
Is there a way to use RestSharp from a local file? I was going to try to use the same function regardless of whether the xml is local or remote and just pass it the location of the xml to read.
This is in fact possible using built in JsonDeserializer class as below. I have used this method to stub API response for testing.
// Read the file
string fileContents = string.Empty;
using (System.IO.StreamReader reader = new System.IO.StreamReader(#"C:\Path_to_File.txt"))
{
fileContents = rd.ReadToEnd();
}
// Deserialize
RestResponse<T> restResponse = new RestResponse<T>();
restResponse.Content = fileContents;
RestSharp.Deserializers.JsonDeserializer deserializer = new RestSharp.Deserializers.JsonDeserializer();
T deserializedObject = deserializer.Deserialize<T>(restResponse);
This is not possible with standard functionality. For example "file://" URLs do not work with RestSharp.
I would recommend using RestSharp do get the returned data from a Uri and having another function to deserialize this data into an object.
You can use the same funcion then to deserialize from file data.
RestSharp is a library to do REST calls, not to deserialize from arbitrary sources. Even if there is a possibility to make RestSharp believe it is talking to a website instead of a file, it would be a hack.
If you need it you could still use the XmlDeserializer from RestSharp. It expects a IRestResponse object, but it only uses the Content property from it, so it should be easy to create. It still feels like a hack though and there are more than enough other XmlSerializers out there that will do a great job

JsonObject in .NET for Windows Store App

I get a response string from an API by using this code :
HttpResponseMessage response = await client.GetAsync(url);
string responseText = await response.Content.ReadAsStringAsync();
However I'm unable to find out how to initialize a JsonObject since in .NET for WinRT the constructor JsonObject() doesn't take any arguments. For memory I could have made like that in the "regular" .NET Framework :
JsonObject root = new JsonObject(responseText);
What I've missed ?
If you want to serialize the response as a JsonObject you should use JsonObject.Parse(string) or JsonObject.TryParse(string, out JsonObject) methods.
Unless you are truly needing to parse/traverse a JSON encoded string, perhaps all you need to is deserialize it. Here are Microsoft docs on doing that.
Deserialize JSON Encoded String
I personally like working with Newtonsoft's JSON API for this task.
MyObject obj = JsonConvert.DeserializeObject<MyObject>(jsonEncodedString);
Newtonsoft's JSON API
Hope this helps.

Categories

Resources