for 3 days i'm trying to send my object to my webapi. I just can't do it from c# :/
I was trying PostAsync method, i was trying to send json (but then I can't deserialize), i was trying to use JObject but can't do nothing with it. I just don't know how to do this.
I got rly simple method
public string PostMethod(Location param)
{
var test = param;
return test.name;
}
how can I send Location object from c# so I won't get null in webapi ? Only thing i've achived is to send a simple type like 'string'. But none of my metrhods works with more complex objects.
Below Location object
public partial class Location
{
public Location()
{
this.Category = new HashSet<Category>();
}
public int id { get; set; }
public Nullable<System.DateTime> create_date { get; set; }
public Nullable<System.DateTime> modify_date { get; set; }
public Nullable<int> create_user_id { get; set; }
public Nullable<int> modify_user_id { get; set; }
public string name { get; set; }
public string description { get; set; }
public Nullable<int> photo_id { get; set; }
public string www { get; set; }
public string count_data { get; set; }
public string status { get; set; }
public Nullable<double> latitude { get; set; }
public Nullable<double> longitude { get; set; }
public string city { get; set; }
public string country { get; set; }
public string zip { get; set; }
public string telephone { get; set; }
public string street { get; set; }
public virtual AzureMedia AzureMedia { get; set; }
public virtual Users Users { get; set; }
public virtual Users Users1 { get; set; }
public virtual ICollection<Category> Category { get; set; }
}
Did you install the newest Web API from NuGet? And you need the Json.NET too for this.
This should do the trick:
Location loc = new Location( ..... );
var jsonFormatter = new JsonMediaTypeFormatter();
HttpContent content = new ObjectContent<Location>(loc , jsonFormatter);
HttpResponseMessage responseMessage = client.PostAsync(uri, content).Result;
Related
I am new to both .NET Core home somebody can guide me through this.
I need to make a request to this url and save the data into database:
url:
https://covid19.mathdro.id/api
JSON output looks like this:
{"confirmed":{"value":303001,"detail":"https://covid19.mathdro.id/api/confirmed"},"recovered":{"value":91669,"detail":"https://covid19.mathdro.id/api/recovered"},"deaths":{"value":12762,"detail":"https://covid19.mathdro.id/api/deaths"},"dailySummary":"https://covid19.mathdro.id/api/daily","dailyTimeSeries":{"pattern":"https://covid19.mathdro.id/api/daily/[dateString]","example":"https://covid19.mathdro.id/api/daily/2-14-2020"},"image":"https://covid19.mathdro.id/api/og","source":"https://github.com/mathdroid/covid19","countries":"https://covid19.mathdro.id/api/countries","countryDetail":{"pattern":"https://covid19.mathdro.id/api/countries/[country]","example":"https://covid19.mathdro.id/api/countries/USA"},"lastUpdate":"2020-03-21T20:13:21.000Z"}
Model: Totals
public class Total
{
[Key]
public int Id { get; set; }
[Column(TypeName = "int")]
[Required]
public string Confirmed { get; set; }
[Column(TypeName = "int")]
[Required]
public string Recovered { get; set; }
[Column(TypeName = "int")]
[Required]
public string Deaths { get; set; }
[Column(TypeName = "datetime2")]
[Required]
public string LastUpdated { get; set; }
}
My import model:
client.BaseAddress = new Uri("https://covid19.mathdro.id/api");
var response = await client.GetAsync($"");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
I am stuck from here and cant continue.
How do I fetch the data, I need only: confirmed, recovered, deaths and lastUpdate
Pls. anybody help here...
You need to cast JSON to a Class Object. You may get your data like this by using NewtonSoft.Json
using (var client = new HttpClient())
{
string url = string.Format("https://covid19.mathdro.id/api");
var response = client.GetAsync(url).Result;
string responseAsString = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<CovidResult>(responseAsString);
}
public class CovidResult
{
[JsonProperty("confirmed")]
public ValueModel Confirmed { get; set; }
[JsonProperty("recovered")]
public ValueModel Recovered { get; set; }
[JsonProperty("deaths")]
public ValueModel Deaths { get; set; }
}
public class ValueModel
{
[JsonProperty("value")]
public int Value { get; set; }
}
You may fork or download this repo:
https://github.com/fatihyildizhan/CoronaParser
Your modal should be
public class Total
{
public Confirmed confirmed { get; set; }
public Recovered recovered { get; set; }
public Deaths deaths { get; set; }
public string dailySummary { get; set; }
public DailyTimeSeries dailyTimeSeries { get; set; }
public string image { get; set; }
public string source { get; set; }
public string countries { get; set; }
public CountryDetail countryDetail { get; set; }
public DateTime lastUpdate { get; set; }
}
public class Confirmed
{
public int value { get; set; }
public string detail { get; set; }
}
public class Recovered
{
public int value { get; set; }
public string detail { get; set; }
}
public class Deaths
{
public int value { get; set; }
public string detail { get; set; }
}
public class DailyTimeSeries
{
public string pattern { get; set; }
public string example { get; set; }
}
public class CountryDetail
{
public string pattern { get; set; }
public string example { get; set; }
}
If stringResult has an actual value all you have to do is:
JsonConvert.DeserializeObject<Total>(stringResult);
Also when in doubt about the modal you can always use http://json2csharp.com/
I suggest you to use JSon.NET aka Newtonsoft. You can add it from nuget package manager.
Here is the code to map incoming json data to your custom class Total. just add your class contructor which will take json data as argument which is typeof string, and I added one method to make code shorter
public class Total {
public Total(string json) {
JObject jObject = JObject.Parse(json);
Confirmed = GetStringFromJToken(jObject, "confirmed");
Recovered = GetStringFromJToken(jObject, "recovered");
Deaths = GetStringFromJToken(jObject, "deaths");
LastUpdated = (string)jObject["lastUpdate"];
}
private string GetStringFromJToken(JObject jObject, string key) {
JToken keyToken = jObject[key];
return (string)keyToken["value"];
}
[Key]
public int Id { get; set; }
[Column(TypeName = "int")]
[Required]
public string Confirmed { get; set; }
[Column(TypeName = "int")]
[Required]
public string Recovered { get; set; }
[Column(TypeName = "int")]
[Required]
public string Deaths { get; set; }
[Column(TypeName = "datetime2")]
[Required]
public string LastUpdated { get; set; }
}
I am having issues deserializing a nested JSON array from the Genius lyric website API. I formulated the object using http://json2csharp.com. When I deserialize the object, I am unable to access the properties inside of the class, which wasn't entirely unexpected, I am just not sure how to properly design an actual solution to the problem. The JSON object conversions work fine when they are not nested.
What would be the best way to go about handling this?
Here is the conversion code:
string test = await G.SearchGeniusASync(textBox1.Text);
var data = JsonConvert.DeserializeObject<GeniusApiObject>(test);
Here is my class:
class GeniusApiObject
{
public class Meta
{
public int status { get; set; }
}
public class Stats
{
public bool hot { get; set; }
public int unreviewed_annotations { get; set; }
public int concurrents { get; set; }
public int pageviews { get; set; }
}
public class PrimaryArtist
{
public string api_path { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public bool is_meme_verified { get; set; }
public bool is_verified { get; set; }
public string name { get; set; }
public string url { get; set; }
public int iq { get; set; }
}
public class Result
{
public int annotation_count { get; set; }
public string api_path { get; set; }
public string full_title { get; set; }
public string header_image_thumbnail_url { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public int lyrics_owner_id { get; set; }
public string lyrics_state { get; set; }
public string path { get; set; }
public int? pyongs_count { get; set; }
public string song_art_image_thumbnail_url { get; set; }
public Stats stats { get; set; }
public string title { get; set; }
public string title_with_featured { get; set; }
public string url { get; set; }
public PrimaryArtist primary_artist { get; set; }
}
public class Hit
{
public List<object> highlights { get; set; }
public string index { get; set; }
public string type { get; set; }
public Result result { get; set; }
}
public class Response
{
public List<Hit> hits { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public Response response { get; set; }
}
}
This is the source for the SearchGeniusASync method in case it is helpful:
public async Task<string>SearchGeniusASync(string searchParameter)
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", clientAccessToken);
var result = await httpClient.GetAsync(new Uri("https://api.genius.com/search?q=" + searchParameter), HttpCompletionOption.ResponseContentRead);
var data = await result.Content.ReadAsStringAsync();
return data;
}
This is the scope I am given access to:
https://i.imgur.com/9mZMvfp.png
Here's a sample JSON request in plaintext:
https://pastebin.com/iA8dQafW
GeniusApiObject is not needed in the code, but I'll leave it in just because it helps organize things (may be that something else also has a RootObject from the auto-generator).
The problem is that you are trying to deserialize to what is just an empty class, the class itself has no properties, so you can't deserialize to it. You need to deserialize to the GeniusApiObject.RootObject.
var data = JsonConvert.DeserializeObject<GeniusApiObject.RootObject>(test);
Will deserialize to the .RootObject subclass. This is verified working:
Where I'm using File.ReadAllText("test.json") to load the example API data provided.
Here is a .NET Fiddle showing it working (without the root object and only one song in the response). Thanks to #maccttura.
I am trying to figure out how to use the Refit library to make GET requests but I do not know why it is not working. I am following the example on the refit github page. What am I missing? It seems like the GetUser("octocat") method is not working. I've tried searching for other examples on how to use refit but wasn't able to find anything.
private static async void getUser()
{
var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com");
var octocat = await gitHubApi.GetUser("octocat");
}
public class User
{
[JsonProperty("login")]
public string Login { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("avatar_url")]
public string AvatarUrl { get; set; }
[JsonProperty("gravatar_id")]
public string GravatarId { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("html_url")]
public string HtmlUrl { get; set; }
[JsonProperty("followers_url")]
public string FollowersUrl { get; set; }
[JsonProperty("following_url")]
public string FollowingUrl { get; set; }
[JsonProperty("gists_url")]
public string GistsUrl { get; set; }
[JsonProperty("starred_url")]
public string StarredUrl { get; set; }
[JsonProperty("subscriptions_url")]
public string SubscriptionsUrl { get; set; }
[JsonProperty("organizations_url")]
public string OrganizationsUrl { get; set; }
[JsonProperty("repos_url")]
public string ReposUrl { get; set; }
[JsonProperty("events_url")]
public string EventsUrl { get; set; }
[JsonProperty("received_events_url")]
public string ReceivedEventsUrl { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("site_admin")]
public bool SiteAdmin { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("company")]
public string Company { get; set; }
[JsonProperty("blog")]
public string Blog { get; set; }
[JsonProperty("location")]
public string Location { get; set; }
[JsonProperty("email")]
public object Email { get; set; }
[JsonProperty("hireable")]
public object Hireable { get; set; }
[JsonProperty("bio")]
public object Bio { get; set; }
[JsonProperty("public_repos")]
public long PublicRepos { get; set; }
[JsonProperty("public_gists")]
public long PublicGists { get; set; }
[JsonProperty("followers")]
public long Followers { get; set; }
[JsonProperty("following")]
public long Following { get; set; }
[JsonProperty("created_at")]
public System.DateTimeOffset CreatedAt { get; set; }
[JsonProperty("updated_at")]
public System.DateTimeOffset UpdatedAt { get; set; }
}
interface IGitHubApi
{
[Get("/users/{user}")]
Task<User> GetUser(string user);
}
If you want to query GitHub API you need to set a User-Agent
There's 2 way to do this with Refit:
1 - Set the headers on your contract
[Headers("User-Agent: My Favorite User Agent!")]
public interface IGitHubApi
{
[Get("/users/{user}")]
Task<User> GetUser(string user);
}
2 - Use a HttpClient and set it there
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("User-Agent", "My Favorite User Agent!");
httpClient.BaseAddress = new Uri("https://api.github.com");
var gitHubApi = RestService.For<IGitHubApi>(httpClient);
var user = await gitHubApi.GetUser("octocat");
If you are using the Github API than You need to set the UserAgent in the Header,
just as follows,
{
BaseAddress = new Uri("https://api.github.com"),
DefaultRequestHeaders = {UserAgent = { ProductInfoHeaderValue.Parse("NakWarsi")}} //here I have put my username("NakWarsi") what you need to replace with your username
};
_restApiService = RestService.For<IGitHubApi>(_client);
Here I have created a sample project using Github take a look for detailed information
I'm programming a C# implementation for the Qualtrics API (v 2.5) using RestSharp. When calling the method getUserIds, it returns a list of users in JSON format (see the example output below).
The problem/question I face is that for each user object (the list of objects under Result) it generates a different id, starting with URH_. When using json2csharp it assumes ofcourse that it's always a different class, while in fact it's absolutely the same one as you can see in the output, and as is stated in the documentation of the api. How can I best resolve this - so that I can make a class UserData that I can reuse? Because now I obviously always see these random URH_ prefixed classes in each response.
NOTE: I was thinking I could try to massage the response first, and when I get the response replace each URH_ prefixed object under the root Result object with a "UserData" string - but I feel this is breaking the rules a bit, and thought the community would have a better solution?
Below is the raw JSON output (note that I removed sensitive information):
{"Meta":{"Status":"Success","Debug":""},"Result":{"URH_3wpA9pxGbE0c7Xu":{"DivisionID":null,"UserName":"user.name#domain.com","UserFirstName":"x","UserLastName":"x","UserAccountType":"UT_4SjjZmbPphZGKDq","UserEmail":"x.x#x.x","UserAccountStatus":"Active"},"URH_57vQr8MVXgpcPUo":{"DivisionID":"DV_XXXXXXXX","UserName":"jxxxx#xx.xxx","UserFirstName":"X","UserLastName":"X","UserAccountType":"UT_BRANDADMIN","UserEmail":"xxxx#xxg.xxx","UserAccountStatus":"Active"},"URH_6ujW1EP0QJOUaoI":{"DivisionID":"DV_XXXXXXXYZ","UserName":"x.xckx#xxx.xyz","UserFirstName":"x","UserLastName":"x","UserAccountType":"UT_XXXXXABCD","UserEmail":"c.c#cc.com","UserAccountStatus":"Active"}}}
This is what I get when generating a model using json2csharp:
public class Meta
{
public string Status { get; set; }
public string Debug { get; set; }
}
public class URH3wpA9pxGbE0c7Xu
{
public object DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class URH57vQr8MVXgpcPUo
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class URH6ujW1EP0QJOUaoI
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class Result
{
public URH3wpA9pxGbE0c7Xu URH_3wpA9pxGbE0c7Xu { get; set; }
public URH57vQr8MVXgpcPUo URH_57vQr8MVXgpcPUo { get; set; }
public URH6ujW1EP0QJOUaoI URH_6ujW1EP0QJOUaoI { get; set; }
}
public class RootObject
{
public Meta Meta { get; set; }
public Result Result { get; set; }
}
It's simple - just use Dictionary<string, UserData> generic type for Result field:
public class Response
{
public Meta Meta { get; set; }
public Dictionary<string, UserData> Result { get; set; }
}
public class Meta
{
public string Status { get; set; }
public string Debug { get; set; }
}
public class UserData
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
While I am trying to call the
`var obj = JsonConvert.DeserializeObject<UserModel>({myjsonString})`
it keeps throwing me unable to deserialize exception.
To check if my json string was well formed i decided to
Parse the string and called
JsonSchema schema = JsonSchema.Parse({myjsonString});
now i get the error below, not quite sure what it means
Additional information: Expected object while parsing schema object,
got String. Path ''
**UPDATE**
"{\"Id\":5,\"Username\":\"Sid\",\"FirstName\":\"Sid \",\"LastName\":\"LastSid\",\"Email\":\"test#gmail.com\",\"Password\":\"sample\",\"GravatarHash\":\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50\",\"Country\":\"Moon\",\"OrganizationId\":1,\"IsLocked\":false,\"CreatedDate\":\"12/13/2013 2:34:28 AM\",\"UpdatedDate\":\"12/13/2013 2:34:28 AM\",\"DataLoaded\":true}"
UPDATE 2
"\"{\\\"Id\\\":5,\\\"Username\\\":\\\"Sid\\\",\\\"FirstName\\\":\\\"Siddharth \\\",\\\"LastName\\\":\\\"Kosta\\\",\\\"Email\\\":\\\"Skosta#gmail.com\\\",\\\"Password\\\":\\\"PAssword\\\",\\\"GravatarHash\\\":\\\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8c4bcd5adc1?d=retro&?s=50\\\",\\\"Country\\\":\\\"India\\\",\\\"OrganizationId\\\":1,\\\"IsLocked\\\":false,\\\"CreatedDate\\\":\\\"2013-12-13T02:34:28.037\\\",\\\"UpdatedDate\\\":\\\"2013-12-13T02:34:28.23\\\",\\\"DataLoaded\\\":true}\""
The User Model
public class UserModel
{
public Int32 Id { get; set; }
public String Username { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public String GravatarHash { get; set; }
public String Country { get; set; }
public Int32 OrganizationId { get; set; }
public Boolean IsLocked { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime UpdatedDate { get; set; }
}
I also tried
public String CreatedDate { get; set; }
public String UpdatedDate { get; set; }
thinking if the dates were causing a problem
Update:
It works perfectly fine with your UserModel, at least for me.
Assume you have such UserModel:
public class UserModel
{
public int Id { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string GravatarHash { get; set; }
public string Country { get; set; }
public int OrganizationId { get; set; }
public bool IsLocked { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime UpdatedDate { get; set; }
public bool DataLoaded { get; set; }
}
var input =
"{\"Id\":5,\"Username\":\"Sid\",\"FirstName\":\"Sid \",\"LastName\":\"LastSid\",\"Email\":\"test#gmail.com\",\"Password\":\"sample\",\"GravatarHash\":\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50\",\"Country\":\"Moon\",\"OrganizationId\":1,\"IsLocked\":false,\"CreatedDate\":\"12/13/2013 2:34:28 AM\",\"UpdatedDate\":\"12/13/2013 2:34:28 AM\",\"DataLoaded\":true}";
var userModel = JsonConvert.DeserializeObject<UserModel>(input);
I think the problem with your model, can you please provided it?
It looks to me like your JSON is getting double serialized. (Having a bunch of extra backslashes in your JSON is a symptom of this.) I notice in the comments on another answer that you said you are using Web API. The Web API framework takes care of serialization for you, so you do not need to call JsonConvert.SerializeObject() in those methods. Instead just return your result directly. Then you should be able to deserialize it normally in your client. See this question.
Is there a reason why you have the curly braces in
var obj = JsonConvert.DeserializeObject<UserModel>({myjsonString})
That seems like the source of the error. Change it to:
var obj = JsonConvert.DeserializeObject<UserModel>(myjsonString)
You're missing the DataLoaded property.
public bool DataLoaded { get; set; }
In future, use this website to generate your C# classes from JSON.
http://json2csharp.com/
EDIT:
Try this step by step...
Copy and paste this class exactly as is.
public class UserModel
{
public int Id { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string GravatarHash { get; set; }
public string Country { get; set; }
public int OrganizationId { get; set; }
public bool IsLocked { get; set; }
public string CreatedDate { get; set; }
public string UpdatedDate { get; set; }
public bool DataLoaded { get; set; }
}
Now in the console have this:
var jsonString = #"{""Id"":5,""Username"":""Sid"",""FirstName"":""Sid "",""LastName"":""LastSid"",""Email"":""test#gmail.com"",""Password"":""sample"",""GravatarHash"":""http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50"",""Country"":""Moon"",""OrganizationId"":1,""IsLocked"":false,""CreatedDate"":""12/13/2013 2:34:28 AM"",""UpdatedDate"":""12/13/2013 2:34:28 AM"",""DataLoaded"":true}";
var user = JsonConvert.DeserializeObject<UserModel>(jsonString);
Console.WriteLine(user.Country);
Console.ReadLine();