How can I use restsharp by calling get method? - c#

My question is simple. I want to learn restsharp because of that. I used fake restful service "https://jsonplaceholder.typicode.com/posts" but queryResult is null what is wrong with it? how can ı get json data from "https://jsonplaceholder.typicode.com/posts" by using restsharp?
using RestSharp;
using System;
using System.Collections.Generic;
namespace ConsoleApp1.RestfulWebServ
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://jsonplaceholder.typicode.com/");
var request = new RestRequest("posts/", Method.GET);
var queryResult = client.Execute<List<Person>>(request).Data;
}
}
internal class Person
{
public int userId { get; set; }
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
}
}

Related

JsonSerializer.Deserialize<T>(); in System.Text.Json not deserialize correctly

I'm trying to deserialize this json with System.Text.Json, but I can't, and I don't know why it's not working, here's the result:
PS: And I don't know if that influences, but the array where the elements are inside, has no name, just enter the link and see
PS/2: This happens on any object in the list
Here is my code:
using System.Text.Json.Serialization;
namespace AceOfSpadesServersList
{
internal sealed class ServerList
{
[JsonPropertyName("name")]
public string Name { get; internal set; }
[JsonPropertyName("identifier")]
public string IP { get; internal set; }
[JsonPropertyName("map")]
public string Map { get; internal set; }
[JsonPropertyName("game_mode")]
public string GameMode { get; internal set; }
[JsonPropertyName("country")]
public string Country { get; internal set; }
[JsonPropertyName("latency")]
public ushort Latency { get; internal set; }
[JsonPropertyName("players_current")]
public byte CurrentPlayers { get; internal set; }
[JsonPropertyName("players_max")]
public byte MaxPlayers { get; internal set; }
[JsonPropertyName("last_updated")]
public uint LastUpdated { get; internal set; }
[JsonPropertyName("game_version")]
public string GameVersion { get; internal set; }
}
}
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using AceOfSpadesServersList;
namespace AceOfSpadesServersList
{
public class AceOfSpadesServersList
{
private const string BuildAndShootServersList = "http://services.buildandshoot.com/serverlist.json";
private readonly HttpClient _httpClient;
public AceOfSpadesServersList()
{
if (_httpClient is null)
this._httpClient = new HttpClient();
}
public async Task GetAllServersAsync()
{
var json = string.Empty;
var streamHttpResponse = await this._httpClient.GetStreamAsync(BuildAndShootServersList);
using (var sr = new StreamReader(streamHttpResponse, Encoding.UTF8))
json = await sr.ReadToEndAsync();
var serverList = JsonSerializer.Deserialize<ServerList[]>(json);
}
}
}
I don't know what's wrong, but I tested the exact same code using Newtonsoft.Json, and I just changed the JsonPropertyName attribute to JsonProperty and JsonSerializer.Deserialize<ServerList[]>(json); to JsonConvert.DeserializeObject<ServerList[]>(json); and works normally, it just doesn't work in the standard C# library
System.Text.Json respects the visibility constraints you impose on the class. Remove the internal on your setters.
i have the same problem and fix it by add PropertyNamingPolicy
var serverList = JsonSerializer.Deserialize<ServerList[]>(json, new
JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});

Newtonsoft.Json parsing json from webpage doesn't work

I've made a simple program that gets json from a website. It should give out some of the json attributes, but it doesn't do it. It simply gives me a clear String without text in it. Can someone help me?
My Code:
using System;
using System.Linq;
using System.Diagnostics;
using System.Threading;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace ESEL_Scraper_2._0
{
class MyJsonType
{
public string title { get; set; }
public int id { get; set; }
}
class Program
{
static void Main(string[] args)
{
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
string site = client.DownloadString($"https://esel.at/api/termine/data?date=05.09.2020&selection=false");
var myJsonObject = JsonConvert.DeserializeObject<MyJsonType>(site);
Console.WriteLine(myJsonObject.title);
}
}
}
The JSON: https://esel.at/api/termine/data?date=05.09.2020&selection=false
MyJsonType expects the body to be like,
{
"id": 1,
"title": "title"
}
but in your case, the json is,
{
"termine": [
{ -> object }
{ -> object }
]
}
You have an array of Objects that fit into your MyJsonType. Use the following class to deserialize to
public class RootObject
{
[JsonProperty("termine")] // the name of the property is case sensetive.
public List<MyJsonType> Termine {get;set;}
}
public class MyJsonType
{
[JsonProperty("title")]
public string Title { get; set; } //C# uses uppercase first letter for properties.
[JsonProperty("id")]
public int Id { get; set; }
}
// in your main,
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(obj.Termine.First().Title);
You need to structure your call as per your json string.
You class should look like this
public class ParentJsonType
{
public List<MyJsonType> termine { get; set; }
}
public class MyJsonType
{
public string title { get; set; }
public int id { get; set; }
}
and in your code you can deserialize
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
string site = client.DownloadString($"https://esel.at/api/termine/data?date=05.09.2020&selection=false");
var myJsonObject = JsonConvert.DeserializeObject<List<MyJsonType>>(site);
foreach(var myJosnType in myJsonObject)
{
//add your logic here
Console.WriteLine(myJosnType.title);
}
Yes, guys that already answered are absolutely right.
The point is in the wrong model you have, which has no necessary structure to contain a responded context.
The following approach is also working. The correct model for that JSON should be:
public class Termine
{
public Int64 id {get;set;}//":106102,
public String title {get;set;}//":"curated by 2020",
public String category {get;set;}//":"eSeLs Neugierde",
public String startdate {get;set;}//":"Sa, 05.09.2020",
public String startdatetime {get;set;}//":"Sa, 05.09. 11:00",
public String starttime {get;set;}//":"11:00",
public String enddate {get;set;}//":"Sa, 05.09.2020",
public List<object> runtime {get;set;}//":[ 0, "nur noch heute" ],
public String thumbnail {get;set;}//":"https:\/\/static.esel.at\/mini\/\/upload\/IpeP5wgYL7sRucTuFtpJg53zgG7hby5IiXv5txLk.jpeg",
public String thumbnail_credits {get;set;}//":null,
public String type {get;set;}//":"upcoming",
public String recommended {get;set;}//":"(Wie) Schafft's Kunst als Aktivismus in Galerier\u00e4ume?`",
public Boolean online_event {get;set;}//":false,
public String feed_urls {get;set;}//":null,
public String status {get;set;}//":"",
public String tags {get;set;}//":"Galerienfestival, internationale KuratorInnen, Aktivismus, Kunst, curatedby",
public String url {get;set;}//":"https:\/\/esel.at\/termin\/106102\/curated-by-2020",
public DateTime sort_date {get;set;}//":"2020-09-05 11:00:00",
public String sort_category {get;set;}//":"eselsneugierde",
public String location_url {get;set;}//":"https:\/\/esel.at\/location\/933\/wien",
public String location {get;set;}//":"Wien"
public override String ToString(){
return String.Format("[{0}] {1} ({2})", this.id, this.title, this.location_url);
}
}
public class Meta
{
public List<String> next {get;set;}//":[ "Sonntag,<br><nobr>06. September 2020<\/nobr>", "06.09.2020", "06092020" ],
public DateTime now {get;set;}//":"2020-09-05T18:52:05.000040Z",
public List<String> da {get;set;}//":[ "Samstag,<br><nobr>05. September 2020<\/nobr>", "05.09.2020", "05092020" ],
public DateTime end {get;set;}//":"2020-09-05T21:59:59.999999Z",
public DateTime runtime {get;set;}//":"2020-09-04T22:00:00.000000Z",
public Int32 upcoming {get;set;}//":14
public Int32 running {get;set;}//":87,
public Int64 termine {get;set;}//":16
}
public class Context
{
public List<Termine> termine{get;set;}
public Meta meta {get;set;}
}
So, your code will work with a few changes:
public static void Main(string[] args)
{
WebClient client = new WebClient()
{
Encoding = System.Text.Encoding.UTF8
};
string site = client.DownloadString("https://esel.at/api/termine/data?date=05.09.2020&selection=false");
Context ctx = JsonConvert.DeserializeObject<Context>(site);
ctx.termine.ForEach(Console.WriteLine);
}
Here is the link to the full solution where you can run and test.
https://dotnetfiddle.net/elq5Lv

Json Deserializer in C# is returning Incorrect Values from Json Request Response

I am attempting to return the Json response deserialized from the following https://www.supremenewyork.com/mobile_stock.json
Below is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Text;
using System.Drawing;
using System.IO;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using RestSharp;
using System.Threading.Tasks;
using System.Globalization;
namespace SupremeMobileMonitor
{
class Program
{
static async Task Main(string[] args)
{
var program = new Program();
await program.GetItem();
}
// Declaring variables in the list
static List<ItemDetail> ProductList = new List<ItemDetail>();
List<string> productDesc = new List<string> { "new_item", "price", "category", "imageurl", "itemURL" };
List<string> category = new List<string> { "jackets", "shirts", "tops_sweaters", "pants", "hats", "accessories", "shoes", "skate" };
//creating a class for intializing Json Deserializer
public class MobileStockResponse
{
[JsonProperty("unique_image_url_prefixes")]
public List<object> UniqueImageUrlPrefixes { get; set; }
[JsonProperty("products_and_categories")]
public Dictionary<string, List<ProductsAndCategory>> ProductsAndCategories { get; set; }
[JsonProperty("release_date")]
public string ReleaseDate { get; set; }
[JsonProperty("release_week")]
public string ReleaseWeek { get; set; }
}
public partial class ProductsAndCategory
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("image_url")]
public string ImageUrl { get; set; }
[JsonProperty("image_url_hi")]
public string ImageUrlHi { get; set; }
[JsonProperty("price")]
public long Price { get; set; }
[JsonProperty("sale_price")]
public long SalePrice { get; set; }
[JsonProperty("new_item")]
public bool NewItem { get; set; }
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("category_name")]
public string CategoryName { get; set; }
}
//Initializing HttpClient for Requests and po
public async Task GetItem()
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
RequestUri = new Uri("https://www.supremenewyork.com/mobile_stock.json"),
Method = HttpMethod.Get
};
var response = await client.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
var responseObject = JsonConvert.DeserializeObject<ProductsAndCategory>(responseContent);
Console.WriteLine(responseObject);
}
}
}
When I try to return a value (example: responseObject.id) It will just return '0'
When I try to return the complete response, it returns "SupremeMobileMonitor.Program+ProductsAndCategory"
Any idea why I can't get it returned and what I'm messing up my deserialization? Unfortunately the category known as "new" on the endpoint interferes with the C# keywords therefore removing my option to use dynamic deserialization.
jslowik has the correct answer for your question, how to deserialize it.
To Print the object, you can either create an override ToString() method and print out only the things you are interested in, or you can print the object by serializing it to a string.
Console.WriteLine(JsonConvert.SerializeObject(productsAndCategories, Formatting.Indented);
This will give you a json representation again of the object and show you all the values.
SideNote: If you want to get specific items from, Say, Bags, you can use Linq to get it...
Console.WriteLine(JsonConvert.SerializeObject(responseObject.ProductsAndCategories["Bags"].Select(x => x.Id)));
// Output:
[173389,172978,173019,172974,173018,173001]
Off hand I would just deserialize the full object. Example:
// Full model represented by your class
var responseObject = JsonConvert.DeserializeObject<MobileStockResponse>(responseContent);
// The products and categories dictionaries you're looking for
var productsAndCategories = responseObject.ProductsAndCategories;

Traversing an XML file using Linq to XML not working as expected

Sorry for the somewhat basic question, but what can I say. I can't figure it out. The problem is that there's a foreach loop that's supposed to iterate through the rows (sections) and while it works for the first section, the second time through the loop it doesn't seem to read the second section. The same data is stored in version. BTW, the way the method is called I would be passing in ProductName as a parameter (There will be multiple products represented here and also a version number (e.g. v2.0.0) that I'll need to filter the results for too.
So I have an XML file that looks like this:
<Products>
<ProductName1>
<v2.0.0>
<GUID>"{B5ECEC43-5406-4E4D-96D9-456823100313}"</GUID>
<VersionNameToUninstall>"2.0.0 - 2.0.2"</VersionNameToUninstall>
<UninstallResponseFile>"GVQC-Client-2.0.0-Uninst.iss"</UninstallResponseFile>
</v2.0.0>
<v2.0.3>
<GUID>"{1D6C02D7-8E87-43BE-8AB2-1FF0E5ACD410}"</GUID>
<VersionNameToUninstall>"2.0.3"</VersionNameToUninstall>
<UninstallResponseFile>"GVQC-Client-2.0.3-Uninst.iss"</UninstallResponseFile>
</v2.0.3>
</ProductName1>
<ProductName2>
<v3.0.0>
<GUID>"{ABCDEC43-5406-4E4D-96D9-456823101234}"</GUID>
<VersionNameToUninstall>"2.2.0 - 2.2.2"</VersionNameToUninstall>
<UninstallResponseFile>"GVQC-Client-2.2.0-Uninst.iss"</UninstallResponseFile>
</v3.0.0>
<v4.0.0>
<GUID>"{5D6C02D7-8E87-43BE-8AB2-1FF0E5ACD589}"</GUID>
<VersionNameToUninstall>"4.0.0"</VersionNameToUninstall>
<UninstallResponseFile>"GVQC-Client-4.0.0-Uninst.iss"</UninstallResponseFile>
</v4.0.0>
</ProductName2>
</Products>
There will only be 10 or so versions (e.g. v2.x.x) so there's not a lot of data here. So I created a multidimensional (nested) class/struct to hold the data and when I try my code to read the data it's not working.
Here are the classes/stucts (I've tried both and neither works) that I'm trying to populate:
public class TopLevelObject
{
public string Version { get; set; }
public RowLevelObject Row {get;set;}
}
public struct RowLevelObject
{
public string Guid { get; set; }
public string VersionName { get; set; }
public string UninstallFileName { get; set; }
}
So here's my code. Please just ignore the Stream - that's so I can embed this XML file in the .exe and not have it be a separate file:
public static List<TopLevelObject> GetGUIDSFromFile(string GUIDKey)
List<InstallScriptMSIXMLTopLevelObject> installScriptMSIXMLTopLevelObjectList = new List<InstallScriptMSIXMLTopLevelObject>();
Stream GUIDXmlFileStream = typeof(PGCommonCA).Assembly.GetManifestResourceStream("PGCommonCA.ProductGUIDs.xml");
XElement xElement = XElement.Load(GUIDXmlFileStream);
var versions = xElement.Elements(GUIDKey).Descendants();
foreach (var version in versions)
{
TopLevelObject topLevelObject = new TopLevelObject();
RowLevelObject rowLevelObject = new RowLevelObject();
TopLevelObject.Version = version.Name.LocalName;
RowLevelObject.Guid = version.Element("GUID").Value;
RowLevelObject.VersionName = version.Element("VersionNameToUninstall").Value;
RowLevelObject.UninstallFileName = version.Element("UninstallResponseFile").Value;
TopLevelObjectList.Add(topLevelObject);
}
return TopLevelObjectList;
}
I know there are many ways to read XML and my choice doesn't work so I'm looking for another simple solution.
The following works :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement productName = doc.Root;
List<TopLevelObject> top = productName.Elements().Select(x => new TopLevelObject() {
Version = x.Name.LocalName,
Row = new RowLevelObject() {
Guid = (string)x.Element("GUID"),
VersionName = (string)x.Element("VersionNameToUninstall"),
UninstallFileName = (string)x.Element("UninstallResponseFile")
}
}).ToList();
}
}
public class TopLevelObject
{
public string Version { get; set; }
public RowLevelObject Row { get; set; }
}
public struct RowLevelObject
{
public string Guid { get; set; }
public string VersionName { get; set; }
public string UninstallFileName { get; set; }
}
}
I figured it out (many thanks to jdweng!!). Here's the final solution based on the revised XML at the top:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static TopLevelObject GetInfo(string xmlKey)
{
XDocument doc = XDocument.Load(FILENAME);
XElement productName = doc.Root;
List<TopLevelObject> top = productName.Descendants(xmlKey).Elements().Select(x => new TopLevelObject() {
Version = x.Name.LocalName,
Row = new RowLevelObject() {
Guid = (string)x.Element("GUID"),
VersionName = (string)x.Element("VersionNameToUninstall"),
UninstallFileName = (string)x.Element("UninstallResponseFile")
}
}).ToList();
}
}
public class TopLevelObject
{
public string Version { get; set; }
public RowLevelObject Row { get; set; }
}
public struct RowLevelObject
{
public string Guid { get; set; }
public string VersionName { get; set; }
public string UninstallFileName { get; set; }
}
}

Visual Studio C# How to parse and list each record/field of a json webservice

Below is the json text I receive for a test web service and looking for how it each record field could be displayed .
{"records":[
{"id":"10","email":"bcomecomaaacomea#myhost.om","name":"Dot"},{"id":"855","email":"webcastpoa0#myhost","name":"name_0"},{"id":"856","email":"webcastpoa1#myhost","name":"name_1"},{"id":"857","email":"webcastpoa2#myhost","name":"name_2"},{"id":"858","email":"webcastpoa3#myhost","name":"name_3"},{"id":"859","email":"webcastpoa4#myhost","name":"name_4"},{"id":"860","email":"webcastpoa5#myhost","name":"name_5"},{"id":"861","email":"webcastpoa6#myhost","name":"name_6"},{"id":"862","email":"webcastpoa7#myhost","name":"name_7"},{"id":"863","email":"webcastpoa8#myhost","name":"name_8"},{"id":"864","email":"webcastpoa9#myhost","name":"name_9"},{"id":"865","email":"webcastpoa10#myhost","name":"name_10"},{"id":"866","email":"webcastpoa11#myhost","name":"name_11"},{"id":"867","email":"webcastpoa12#myhost","name":"name_12"},{"id":"868","email":"webcastpoa13#myhost","name":"name_13"},{"id":"869","email":"webcastpoa14#myhost","name":"name_14"},{"id":"870","email":"webcastpoa15#myhost","name":"name_15"},{"id":"871","email":"webcastpoa16#myhost","name":"name_16"},{"id":"872","email":"webcastpoa17#myhost","name":"name_17"},{"id":"873","email":"webcastpoa18#myhost","name":"name_18"},{"id":"874","email":"webcastpoa19#myhost","name":"name_19"},{"id":"875","email":"webcastpoa20#myhost","name":"name_20"},{"id":"876","email":"webcastpoa21#myhost","name":"name_21"},{"id":"877","email":"webcastpoa22#myhost","name":"name_22"},{"id":"878","email":"webcastpoa23#myhost","name":"name_23"},{"id":"879","email":"webcastpoa24#myhost","name":"name_24"},{"id":"880","email":"webcastpoa25#myhost","name":"name_25"},{"id":"881","email":"webcastpoa26#myhost","name":"name_26"},{"id":"882","email":"webcastpoa27#myhost","name":"name_27"},{"id":"883","email":"webcastpoa28#myhost","name":"name_28"},{"id":"884","email":"webcastpoa29#myhost","name":"name_29"},{"id":"885","email":"webcastpoa30#myhost","name":"name_30"},{"id":"886","email":"webcastpoa31#myhost","name":"name_31"},{"id":"887","email":"webcastpoa32#myhost","name":"name_32"},{"id":"888","email":"webcastpoa33#myhost","name":"name_33"},{"id":"889","email":"webcastpoa34#myhost","name":"name_34"},{"id":"890","email":"webcastpoa35#myhost","name":"name_35"},{"id":"891","email":"webcastpoa36#myhost","name":"name_36"},{"id":"892","email":"webcastpoa37#myhost","name":"name_37"},{"id":"893","email":"webcastpoa38#myhost","name":"name_38"},{"id":"894","email":"webcastpoa39#myhost","name":"name_39"},{"id":"895","email":"webcastpoa40#myhost","name":"name_40"},{"id":"896","email":"webcastpoa41#myhost","name":"name_41"},{"id":"897","email":"webcastpoa42#myhost","name":"name_42"},{"id":"898","email":"webcastpoa43#myhost","name":"name_43"},{"id":"899","email":"webcastpoa44#myhost","name":"name_44"}
]}
I have the following code so far.
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Net;
using System.IO;
using Newtonsoft.Json;
WebClient client = new WebClient();
string reply = client.DownloadString("http://192.168.1.115/php_poa/test_select.php");
MessageBox.Show(reply);
records p1 = JsonConvert.DeserializeObject<records>(reply);
MessageBox.Show(p1.ToString());
class records
{
public string id { get; set; }
public string email { get; set; }
public string name { get; set; }
}
And would like a for loop to process each record.
THanks
Just use List<record> instead. You won't require to iterate it through loop.
Example:
List<records> p1 = JsonConvert.DeserializeObject<List<records>>(reply);
Remember to add following namespace at top
using System.Collection.Generic;
You need to use next class for deserialization:
class MyResponse
{
public List<Records> Records { get; set; }
}
class Records
{
public string Id { get; set; }
public string Email { get; set; }
public string Name { get; set; }
}
And now you can deserialize your web response:
MyResponse myResponse = JsonConvert.DeserializeObject<MyResponse>(reply);
to iterate through a loop you can do something like this
JObject records = JObject.Parse(json);
foreach (var record in obj["records"])
{
records p1 = JsonConvert.DeserializeObject<records>(reply);
}
although i would suggest creating a constructor for your class instead of using DeserializeObject
like this
public Records(JToken toekn)
{
Id = (string)toekn["Id "];
Email = (string)toekn["Email "];
Name = (string)toekn["Name "];
}
and use
Records record = new Records(record) instead of DeserializeObject inside the loop

Categories

Resources