JsonObject in .NET for Windows Store App - c#

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.

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.

Converting a XML Object into JSON from OpenWeatherMap API

I have created a basic ASP.Net Web Application and I am trying to use the OpenWeatherMap API with this. (first time dealing with APIs).
The Info I have about the WebAPI is:
You can search weather forecast for 5 days with data every 3 hours by city name. All weather data can be obtained in JSON and XML formats.
There is a possibility to receive a central district of the city/town with its own parameters (geographic coordinates/id/name) in API response. Example
API call:
api.openweathermap.org/data/2.5/forecast?q={city name},{country code}
Parameters:
q city name and country code divided by comma, use ISO 3166 country codes
Examples of API calls:
api.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml
Currently I have this working when I use the api that returns a json object
api.openweathermap.org/data/2.5/weather?q=London&units=metric
However if I simply change the URL to the first (which returns the XML) my application no longer retrieves the data from the API.
I have tried amended the mode=xml into mode=json but still no avail.
How can I use the first web API?
Many thanks
--Edit:
In my model class i have the following method:
string url = "api.openweathermap.org/data/2.5/…;
var client = new WebClient();
var content = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var jsonContent = serializer.Deserialize<Object>(content);
return jsonContent;
(taken out the key) I then call this method from my view. However I cannot use that api call that has the =xml at the end
your problem is when result is returned as xml, you are using a JavaScriptSerializer to Deserialize it.
xml is not json, hence the Deserialization would have failed
what you need is a XmlSerializer to deserializae the result
below is some code to get you started:
string url = #"http://samples.openweathermap.org/data/2.5/forecast?q=London&appid=b1b15e88fa797225412429c1c50c122a1&mode=xml";
var client = new WebClient();
var content = client.DownloadString(url);
XmlSerializer serializer = new XmlSerializer(typeof(weatherdata));
weatherdata result = null;
using (TextReader reader = new StringReader(content))
{
result = (weatherdata)serializer.Deserialize(reader);
}
notice that typeof weatherdata - it is no point of Deserialize into non strong type object if you are going to deserialize into object,
there is noting you can do with it.
if you don't want to hand code the strong type model, copy the xml result into clipboard then use VS (not sure other version but 2017 as example) toolbar
Edit -> paste special -> Paste xml as classes to generate the strong type class for you

Using Protobuf in .Net Core with .proto files

I'm looking into using Protobuf to send data between my Microservices, and
I'm using the C# support in Google.ProtoBuf and not ProtoBuf-Net, since I want to compile classes from .proto files.
The reason for this is the Microservices are not strictly .Net. Some of the are written in Go etc.
I'm looking for something like the ProtoBufFormatter in the package WebApiContrib.Formatting.ProtoBuf, but support Google.ProtoBuf.
The ProtoBufFormatter returns serialized protobuf data if the client have set content type to application/x-protobuf, otherwise Json.
How can I achieve something similar for Google.ProtoBuf? Further I'm also looking into find this kind of support for the Nancy Framework on .Net Core as well.
I have found this link where it explains how to use protobuf files with Protobuf-Net, but does not seem up to date (.Net Core + VSCode).
I could not find any solution for my use case with Google.Protobuf, so I used a custom InputFormatter and OutputFormatter like in this blog post, with Protobuf-Net.
Then to call and deserialize the protobuf content in the client, I came up with this solution:
var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("api/home");
if (response.IsSuccessStatusCode)
{
if (response.Content.Headers.ContentType.MediaType == "application/x-protobuf")
{
using(var stream = await response.Content.ReadAsStreamAsync())
{
var protoBufModel = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream);
return $"{protoBufModel.Name}, {protoBufModel.StringValue}, {protoBufModel.Id}";
}
}
var content = await response.Content.ReadAsStringAsync();
var jsonModel = JsonConvert.DeserializeObject<ProtobufModelDto>(content);
return $"{jsonModel.Name}, {jsonModel.StringValue}, {jsonModel.Id}";
}
return "Failed";
Next step will be to figure out how to create models from .proto files with Protobuf-Net.

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

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.

Categories

Resources