How to capture JSON request message - c#

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);

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.

How to get a raw json as a parameter

I wanna get a raw json string from my client in my WebAPI application.
I tried it like this :
public string Get([FromBody]string rawjson)
{
}
I use Google Chrome Rest Console to try my methods first. I add my json content to RAW body and then send a get request.I put a breakpoint on my method to see if i can get the raw json data however, method invokes but rawjson comes as null. I've also tried put but that didn't work either.
What am i doing wrong ?
Thanks
GET methods cannot have Request Body and as such cannot parse values using [FromBody]. Please use the POST method.
Change the rawJson parameter type to Stream you will recieve anything that is posted on your service as as stream and than you can just read that stream to string

Store json in variable

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.

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