Deserializing rest client response from wordpress.org - c#

I have a wordpress.org locally hosted on my pc.
I've installed a wordpress plugin called json-api which let you retrieve posts from your wordpress site.
I'm running the following code:
var client = new RestClient(BlogArticlesUrl);
var request = new RestRequest();
request.Timeout = 5000;
request.RequestFormat = DataFormat.Json;
request.Method = Method.GET;
request.AddParameter("json", "get_tag_posts");
request.AddParameter("slug", "featured");
request.AddParameter("count", "3");
var articles = client.Execute<List<BlogArticleModel>>(request);
After executing the code, in the variable articles I have the following:
Inside the Content there are few keys but I would only like to convert 'posts' to a model in c#
How do I acheive that?
EDIT:
I have found a solution using newtonsoft for dot net
Newtonsoft.Json.JsonConvert.DeserializeObject<BlogArticleResponse>(articles.Content);

In RestSharp, the Content is what gets deserialized. So, the type you pass into the .Execute<T> method must be the same structure as the response.
In your case, it will look something like this:
public class BlogArticleResponse
{
public string status { get; set; }
public int count { get; set; }
public int pages { get; set; }
public BlogTag tag { get; set; }
...
}
public class BlogTag
{
public int id { get; set; }
public string slug { get; set; }
public string title { get; set; }
public string description { get; set; }
...
}
You can then execute the request like this:
var result = client.Execute<BlogArticleResponse>(request);
For more information, have a look at the documentation.

Related

Unable to deserialize list in a XML Response using ReadAsAsync<T>

[Update: This question is different from the suggested duplicate because this one is about deserialization of XML and the explanation of the problem and solution on this one is clearer as I've included the full source code.]
I'm trying to read and subsequently manipulate a response from a Web API. Its response looks like this:
<MYAPI xsi:noNamespaceSchemaLocation="MYAPI.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<MySite Resource="some resource name">
<Name>some name</Name>
<URL>some url</URL>
<SecondName>Describes something</SecondName>
</MySite>
... A lot of these <MySite>...</MySite> are there
<SomeOtherSite Resource="some resource name">
<Name>some name</Name>
<URL>some url</URL>
</SomeOtherSite>
</MYAPI>
SomeOtherSite is not repeating and only one of it appears at the end of the response. But the MySite is the one that is repeating.
I've modeled the class for this XML response as:
public class MYAPI
{
public List<MySite> MySite { get; set; }
public SomeOtherSite SomeOtherSite { get; set; }
}
public class MySite
{
public string Name { get; set; }
public string URL { get; set; }
public string SecondName { get; set; }
}
public class SomeOtherSite
{
public string Name { get; set; }
public string URL { get; set; }
}
And this is my code:
static void Main()
{
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential("MyUsername", "MyPassword");
var client = new HttpClient(handler);
client.BaseAddress = new Uri("https://sitename.com:PortNumber/");
var formatters = new List<MediaTypeFormatter>()
{
new XmlMediaTypeFormatter(){ UseXmlSerializer = true }
};
var myApi = new MYAPI();
HttpResponseMessage response = client.GetAsync("/api/mysites").Result;
if (response.IsSuccessStatusCode)
{
myApi = response.Content.ReadAsAsync<MYAPI>(formatters).Result;
}
}
Now the myApi only has object for SomeOtherSite but the list for the MySite is empty.
Would someone please tell me how I should deserialize this response correctly?
Should I be creating custom media formatter? I have no idea of it by the way.
Also would you please tell me how to model that Resource attribute coming in the response?
And I can't change anything in the WebAPI server. I just need to consume the data from it and use it elsewhere.
Thank You so much!
I solved this after some really good direction from: https://stackoverflow.com/users/1124565/amura-cxg Much Thanks!
The solution was to annotate all the properties with XMLAttributes. And it correctly deserialized the response. And as for the Resource attribute, all I needed was [XmlAttribute(AttributeName="Resource")]
The rest of the source code works as is.
[XmlRoot(ElementName="MYAPI")]
public class MYAPI
{
[XmlElement(ElementName="MySite")]
public List<MySite> MySite { get; set; }
[XmlElement(ElementName="SomeOtherSite")]
public SomeOtherSite SomeOtherSite { get; set; }
}
public class MySite
{
[XmlElement(ElementName="Name")]
public string Name { get; set; }
[XmlElement(ElementName="URL")]
public string URL { get; set; }
[XmlElement(ElementName="SecondName")]
public string SecondName { get; set; }
[XmlAttribute(AttributeName="Resource")]
public string Resource { get; set; }
}
Plus, I didn't need any custom media formatter. And from one of the posts by https://stackoverflow.com/users/1855967/elisabeth , I learned that we should not touch the generated file from xsd.exe tool. So I explicitly set to use the XmlSerializer instead of the DataContractSerializer used by default:
var formatters = new List<MediaTypeFormatter>()
{
new XmlMediaTypeFormatter(){ UseXmlSerializer = true }
};

Asp.NetCore API Controller not getting Data from Json

I have 2 applications, one which posts data to another. When I run the first application the post method in the controller executes but the model or ObjavaDto (objaveList) can't be found so it's null. When I copy-paste the json from var json into Postman everything works. What am I missing?
var json = new JavaScriptSerializer().Serialize(objaveList[2]);
I used [2] just for simplicity reasons because there are a lot of them
string url = "http://localhost:61837/api/Objave";
string result;
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/json");
result = client.UploadString(url, "POST", json);
}
2nd application Controller
namespace StecajeviInfo.Controllers.Api
{
[Route("api/[controller]")]
public class ObjaveController : Controller
{
[HttpPost]
public void Post([FromBody]ObjavaDto objaveList)
{
}
}
}
public class ObjavaDto
{
public string OznakaSpisa { get; set; }
public string NazivOtpravka { get; set; }
public string NazivStecajnogDuznika { get; set; }
public string PrebivalisteStecajnogDuznika { get; set; }
public string SjedisteStecajnogDuznika { get; set; }
public string OIBStecajnogDuznika { get; set; }
public string OglasSeOdnosiNa { get; set; }
public DateTime DatumObjave { get; set; }
public string OibPrimatelja { get; set; }
public string Dokument { get; set; }
}
Sent data looks like this
{
"OznakaSpisa":"St-6721/2015",
"NazivOtpravka":"Rješenje - otvaranje stečajnog postupka St-6721/2015-7",
"NazivStecajnogDuznika":"RAIN AIR d.o.o.",
"PrebivalisteStecajnogDuznika":"Savska 144/A, 10000, Zagreb",
"SjedisteStecajnogDuznika":"",
"OIBStecajnogDuznika":‌​"37144498637",
"Oglas‌​SeOdnosiNa":"Missing Oib",
"DatumObjave":"\/Date(1501106400000)\/",
"OibPrimatelja"‌​:"37144498637",
"Doku‌​ment":"e-oglasna.pra‌​vosudje.hr/sites/def‌​ault/files/ts-zg-st/‌​…;"
}
Thank you all for your replies, you have been very helpful and gave me an idea how to test. I tested with commenting out properties and I found out it's because of the special characters in Naziv otpravka ("Rješenje" and "stečajnog") which are luckily present only in that property.
I found that this solved the problem https://stackoverflow.com/a/12081747/6231007
client.Headers["Content-Type"] = "application/json; charset=utf-8";
client.UploadDataAsync(new Uri(url), "POST",
Encoding.UTF8.GetBytes(json));
Datetime is problematic. Make it nullable (DateTime?) and test with that. You'll probably get all other properties filled and datetime will stay null. If that's the problem, make sure your client sends datetime format that your model binder understands.

Calling a Web.Api Post call from asp.net C# applicaiton

so I'm pretty new to using Web.Api calls and have been reading up on them the last few days. In a nutshell I have a C# asp.net application that needs to post records to a Web.Api call that another group has setup for various applications to send records to that I need to interface with. Right now I have something that tries to work but I'm getting 'error 500: Internal server error' when I run things. I admit it could be on their end, but I wanted to make sure my end was correct as well.
So here is what I have. First I have a class I populate and send up to the wab.api call as that is what it is asking for
public class PackageData
{
public string HostName { get; set; }
public string SerialNumber { get; set; }
public int SourceID { get; set; }
public string PackageName { get; set; }
public string UserName { get; set; }
public string BatchID { get; set; }
public DateTime ReceivedTime { get; set; }
}
Here is the function I actually make the call with. Right now for testing purposes I populate a generic 'PackageData' object which I will eventually populate programatically
public string Test_Update()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://ServerName/Updates/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
PackageData InstallPackage = new PackageData();
InstallPackage.HostName = "ComputerName";
InstallPackage.SerialNumber = "SerialNumber";
InstallPackage.PackageName = "PackageName.EXE";
InstallPackage.SourceID = 1;
InstallPackage.UserName = "User";
InstallPackage.BatchID = 1;
InstallPackage.ReceivedTime = DateTime.Now;
HttpResponseMessage response = client.PostAsJsonAsync("api/Package?UserName=UserID&Password=password", InstallPackage).Result;
response.EnsureSuccessStatusCode();
return response.Headers.Location.ToString();
}
Is there anything glaring that looks wrong to anyone?
Thanks for the help!

How to get Json information from web

How can I translate the information from the web source to Json? Registered as json on the web..
According to the values I want to show in the table information
I apologize for the language I use translation
MyCode :
var httpWebRequest = (HttpWebRequest)WebRequest.Create("link");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadLine();
Airport kny = JsonConvert.DeserializeObject<Airport>(result);
string fskodu = kny.fsCode; // fs kodu null whyy???
}
public class Airport
{
[JsonProperty("requestedCode")]
public string requestedCode { get; set; }
[JsonProperty("fsCode")]
public string fsCode { get; set; }
}
Change your class to look like this:
public class RootObject
{
public Request request { get; set; }
}
public class Request
{
public Airport airport { get; set; }
}
public class Airport
{
public string requestedCode { get; set; }
public string fsCode { get; set; }
}
Deserialize with:
var kny = JsonConvert.DeserializeObject<RootObject>(result);
Access values like this:
kny.request.airport.fsCode; // This is == "KYA"
I'm missing out a whole bunch of other properties for brevity, the full class would be a little more complex.
JSON has to be deserialized in its entirety as it represents a complete object, you can't cherry pick one line at a time to get individual properties.

How to grab data off a json URL and place on form?

The following URL represents a long string of data: http://api.bitcoincharts.com/v1/markets.json
I noticed at the end of the url it was a .json extension, so I already researched about that.
Ive downloaded JSON.NET and referenced it in my c#.net source.
Within this long string, I need to get the following data off the "symbol": "mtgoxUSD" and place it on my form;
1) "bid"
2) "high"
3) "ask"
4) "avg"
5) "low"
I am really confused on how to properly extract this data as the URL is one huge string.
The following snippet below is what I have coded so far as I am stumped on how to continue.
public void Grab()
{
using (var tradeClient = new System.Net.WebClient())
{
var json = tradeClient.DownloadString("http://api.bitcoincharts.com/v1/markets.json");
}
}
Please guide me or reference me on how to get started as I have never dealt with a json extension or file before!
Thanks!
You could use JArray array = (JArray) JsonConvert.DeserializeObject(json); using the Newtonsoft.Json.Linq library
try this:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("http://coderwall.com/mdeiters.json");
var arrJson = JsonConvert.DeserializeObject<string[][]>(json);
}
Or you can create an Object/Class and Convert this json into that Object. See this link for your reference. See sample code and class below:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("http://coderwall.com/mdeiters.json");
var jsonMarket = JsonConvert.DeserializeObject<Market>(json);
}
public class Market
{
[JsonProperty("high")]
public string High{ get; set; }
[JsonProperty("latest_trade")]
public string LatestTrade { get; set; }
[JsonProperty("bid")]
public string Bid{ get; set; }
[JsonProperty("volume")]
public string Volume{ get; set; }
[JsonProperty("currency")]
public string Currency{ get; set; }
[JsonProperty("currency_volume")]
public string CurrencyVolume{ get; set; }
[JsonProperty("ask")]
public string Ask { get; set; }
[JsonProperty("close")]
public string Close { get; set; }
[JsonProperty("avg")]
public string AVG { get; set; }
[JsonProperty("symbol")]
public string Symbol { get; set; }
[JsonProperty("low")]
public string Low { get; set; }
}

Categories

Resources