I apologize for this post because it may seem banal to some people. But I would like to understand the operation of the GET API, unfortunately, somehow I have not found an accessible tutorial. As the best way to learn from examples, could anyone show me how to get the values from the name tag in the easiest way? can be up to textBox.
In xml:
https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=xml
In json:
https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json
Code
public class Result
{
public string id { get; set; }
public string name { get; set; }
public bool hasVariables { get; set; }
public List<string> children { get; set; }
public string levels { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
using (WebClient wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
var json = wc.DownloadString("https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json");
Result result = JsonConvert.DeserializeObject<Result>(json);
richTextBox1.Text = result.name;
}
}
Thank you in advance for your help.
You are missing various classes in order to get your JSON string Deserialized properly. Try like:
public class Results
{
public string id { get; set; }
public string name { get; set; }
public bool hasVariables { get; set; }
public List<string> children { get; set; }
public string levels { get; set; }
}
public class Links
{
public string first { get; set; }
public string self { get; set; }
public string next { get; set; }
public string last { get; set; }
}
public class JsonObject
{
public int totalRecords { get; set; }
public int page { get; set; }
public int pageSize { get; set; }
public Links links { get; set; }
public List<Results> results { get; set; }
}
And then use like:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json");
JsonObject result = JsonConvert.DeserializeObject<JsonObject>(json);
foreach (var res in result.results)
{
MessageBox.Show(res.name);
}
}
Related
There are many threads similar to this one, but I couldn't figure out what I wanted.I want to get decimal value from webpage.
This is the website: https://www.lme.com/Metals/Non-ferrous/LME-Aluminium#Trading+day+summary
I will get the aluminum price that I marked in the picture below.
I tried the code stated below but it gets only html codes.
WebClient wb = new WebClient();
String strPageCode = wb.DownloadString("https://www.lme.com/Metals/Non-ferrous/LME-Aluminium#Trading+day+summary");
richTextBox1.Text = strPageCode;
I think I have to inspect page element similar google chrome. For this i tried to selenium nuget package but i couldn't figure out.
Another solution is sendkey CTRL + A and CTRL + C to copy all page contents. Then extract value from clipboard content. But how can i sendkey without openning browser?
In order to grab these values you have to make a GET request to this API endpoint: /api/trading-data/day-delayed?datasourceId=1a0ef0b6-3ee6-4e44-a415-7a313d5bd771
(Base address: https://www.lme.com).
An example for getting these values:
using System.Text.Json;
HttpClient client = new();
client.BaseAddress = new Uri("https://www.lme.com");
var response = await client.GetStringAsync("/api/trading-data/day-delayed?datasourceId=1a0ef0b6-3ee6-4e44-a415-7a313d5bd771");
var table = JsonSerializer.Deserialize<Table>(response);
var bids = table.Rows.Select(r => r.Values[0]);
var offers = table.Rows.Select(r => r.Values[1]);
// POCO
public class Table
{
public Row[] Rows { get; set; }
public string Title { get; set; }
public string Strapline { get; set; }
public string SupportingCopy { get; set; }
public string NoDataMessage { get; set; }
public int DataType { get; set; }
public DateTime DateOfData { get; set; }
public DateTime LookbackDate { get; set; }
public bool HistoricalDataLookbackEnabled { get; set; }
public int HistoricalDataLookbackRange { get; set; }
public int HistoricalDataLookbackUnit { get; set; }
public int HistoricalDataDisplayPeriod { get; set; }
public string[] ColumnTitles { get; set; }
public bool HideColumnTitles { get; set; }
}
public class Row
{
public DateTime BusinessDateTime { get; set; }
public string Ric { get; set; }
public string RowTitle { get; set; }
public DateTime[] BusinessDates { get; set; }
public string[] Values { get; set; }
public string HoverMessage { get; set; }
public string HoverValue { get; set; }
public object HoverValues { get; set; }
public string HoverText { get; set; }
}
I have a JSON document and I want to access the details of the STATUS SECTION but it keeps returning null.
JSON Data is as shown:
{
"results":[
{
"messageId":"15712480583306574",
"to":"",
"from":"TestServer",
"sentAt":"2019-10-16T17:47:38.368+0000",
"doneAt":"2019-10-16T17:47:38.370+0000",
"smsCount":1,
"mccMnc":"null",
"price":{
"pricePerMessage":0.0,
"currency":"USD"
},
"status":{
"groupId":5,
"groupName":"REJECTED",
"id":8,
"name":"REJECTED_PREFIX_MISSING",
"description":"Number prefix missing"
},
"error":{
"groupId":0,
"groupName":"OK",
"id":0,
"name":"NO_ERROR",
"description":"No Error",
"permanent":false
}
}
]
}
C# Code is:
string JsonData = response.Content.ToString();
dynamic results = JsonConvert.DeserializeObject<dynamic>(JsonData);
var statuses = results.status;
foreach(var stat in statuses) {
string groupname = stat.groupName.Value;
string name = stat.name.Value;
string description = stat.description.Value;
}
It keeps returning null, How can I access these members? I am using Newtonsoft.
If you want to access the status object property you need to rewrite your whole code.
string JsonData = response.Content.ToString();
var input = JObject.Parse(str);
var results = input["results"].Children();
var status = results.First()["status"];
string groupname = status["groupName"].ToString();
string name = status["name"].ToString();
string description = status["description"].ToString();
Console.WriteLine(groupname);
Console.WriteLine(name);
Console.WriteLine(description);
The result in Console
REJECTED
REJECTED_PREFIX_MISSING
Number prefix missing
But I would rather use concrete class. You need to create multiple classes. Here is good example.
public class Envelope
{
public List<Item> Results { get; set; }
}
public class Item
{
public Status Status { get; set; }
}
public class Status
{
public int GroupId { get; set; }
public string GroupName { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
After that the usage is much simpler.
string JsonData = response.Content.ToString();
MyEnvelope envelope = JsonConvert.DeserializeObject<MyEnvelope>(JsonData);
var status = envelope.results[0].status;
Console.WriteLine(status.GroupName);
Console.WriteLine(status.Name);
Console.WriteLine(status.Description);
Finest Option: Create A model for the JSON.
public class Price
{
public double pricePerMessage { get; set; }
public string currency { get; set; }
}
public class Status
{
public int groupId { get; set; }
public string groupName { get; set; }
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
}
public class Error
{
public int groupId { get; set; }
public string groupName { get; set; }
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public bool permanent { get; set; }
}
public class Result
{
public string messageId { get; set; }
public string to { get; set; }
public string from { get; set; }
public DateTime sentAt { get; set; }
public DateTime doneAt { get; set; }
public int smsCount { get; set; }
public string mccMnc { get; set; }
public Price price { get; set; }
public Status status { get; set; }
public Error error { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
Then do RootObject results = JsonConvert.DeserializeObject<RootObject>(JsonData);
Fair Option: Get the exact JToken you want.
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string jsonData = "{\"results\":[{\"messageId\":\"15712480583306574\",\"to\":\"\",\"from\":\"TestServer\",\"sentAt\":\"2019-10-16T17:47:38.368+0000\",\"doneAt\":\"2019-10-16T17:47:38.370+0000\",\"smsCount\":1,\"mccMnc\":\"null\",\"price\":{\"pricePerMessage\":0.0,\"currency\":\"USD\"},\"status\":{\"groupId\":5,\"groupName\":\"REJECTED\",\"id\":8,\"name\":\"REJECTED_PREFIX_MISSING\",\"description\":\"Number prefix missing\"},\"error\":{\"groupId\":0,\"groupName\":\"OK\",\"id\":0,\"name\":\"NO_ERROR\",\"description\":\"No Error\",\"permanent\":false}}]}";
JObject jObject = JObject.Parse(jsonData);
Console.WriteLine(jObject.SelectToken("results[0].status"));
}
}
I have a wikipedia api with json format. Now I want to get the extract information from this api. I want to make it dynamic for any wikipedia api. [My wikipedia api][1]. I got following information from jsontoCsharp
namespace Json_deserialize
{
public class pageval
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
}
public class Query
{
public Dictionary<string, pageval> pages { get; set; }
}
public class Limits
{
public int extracts { get; set; }
}
public class RootObject
{
public string batchcomplete { get; set; }
public Query query { get; set; }
public Limits limits { get; set; }
}
class Short_text
{
public static RichTextBox txt1 = new RichTextBox();
public static void shortText()
{
using (WebClient wc = new WebClient())
{
var client = new WebClient();
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Neuschwanstein%20Castle&redirects="); ;
pageval m = JsonConvert.DeserializeObject<pageval>(response);
string result = m.extract;
txt1.Text = result;
}
}
}
}
I want to make such a coding which should be dynamic. That means the id 240912 should be varied in time. I tried a lot. but cannot get a satisfied result.
All JSON objects are essentially dictionaries. However, it usually makes sense to represent them as classes in C#, assuming the schema is constant. For cases where property names are not always the same, it's impossible to write a class to represent the object; so you much use dynamic or a dictionary
public class pageval
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
}
public class Query
{
public Dictionary<string, pageval> pages { get; set; }
}
public class Limits
{
public int extracts { get; set; }
}
public class RootObject
{
public string batchcomplete { get; set; }
public Query query { get; set; }
public Limits limits { get; set; }
}
To get the extract:
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=Neuschwanstein%20Castle&redirects="); ;
var responseJson = JsonConvert.DeserializeObject<RootObject>(response);
var firstKey = responseJson.query.pages.First().Key;
var extract = responseJson.query.pages[firstKey].extract;
I Followed this to Create Restful Web Services which display JSON as OutPut from the MySQL Data base.
I Successfully Done it, But Here I Have nearly 100 Tables in Database with different name
And I am Getting This kind of Json Data
{"WindowsResult":[{"ID":9,"TYPE":"WindowsPhone","TITLE":"XYZ","PRICE":"$0","IMAGE":"Post1.jpg"}],"success":3}
this another result
{"SonyResult":[{"ID":3,"TYPE":"SonyXperia","TITLE":"XYZ","PRICE":"$0","IMAGE":"Post2.jpg"}],"success":3}
this another one
{"SamsungResult":[{"ID":1,"TYPE":"Samsung","TITLE":"XYZ","PRICE":"$0","IMAGE":"Post3.jpg"}],"success":3}
For this I am parsing a JSON data form a url
like localhost/Service1.svc/windows or localhost/Service1.svc/sony like that
Here it should Take with a user input..
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
string Data = txtData.Text;
string ServiceUri = "http://lhost:30576/Service1.svc/"
+ "Data" + "/";
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri(ServiceUri));
}
But I am Confused at Here
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);
foreach (var TYPE in rootObject.SonyResult)
{
Console.WriteLine(type.TITLE);
}
}
what should be at Root object
for some Results I have SamsungResult as Root Object like that.
Please suggest Me Regarding this..
Update
when I enter the a url like http://www.google.com/service1.scv/sony
I am getting
{"SonyResult":[{"ID":3,"TYPE":"SonyXperia","TITLE":"XYZ","PRICE":"$0","IMAGE":"Post2.jpg"}],"success":3}
like that every brand I have one result Not All in one string..
K bro the problem is in your json data
{"Mobiles":[
{"SonyResult":[{"ID":3,"TYPE":"SonyXperia","TITLE":"XYZ","PRICE":"$0","IMAGE":"Post2.jpg"}],"success":3},
{"WindowsResult":[{"ID":9,"TYPE":"WindowsPhone","TITLE":"XYZ","PRICE":"$0","IMAGE":"Post1.jpg"}],"success":3}
]}
Since you hadn't specified a Root object name for our tables so json was using your table names as root objects.
Its C# class will be
public class SonyResult
{
public int ID { get; set; }
public string TYPE { get; set; }
public string TITLE { get; set; }
public string PRICE { get; set; }
public string IMAGE { get; set; }
}
public class WindowsResult
{
public int ID { get; set; }
public string TYPE { get; set; }
public string TITLE { get; set; }
public string PRICE { get; set; }
public string IMAGE { get; set; }
}
public class Mobile
{
public List<SonyResult> SonyResult { get; set; }
public int success { get; set; }
public List<WindowsResult> WindowsResult { get; set; }
}
public class RootObject
{
public List<Mobile> Mobiles { get; set; }
}
Hope that solved your problem.
Update
For ur received query the C# class is going to be
public class SonyResult
{public int ID { get; set; }
public string TYPE { get; set; }
public string TITLE { get; set; }
public string PRICE { get; set; }
public string IMAGE { get; set; }
}
public class RootObject
{
public List<SonyResult> SonyResult { get; set; }
public int success { get; set; }
}
Now since for each different models you are getting different queries where each are an array of its own with no common object name. So for each different model the root object class will differ.
I havent tried it as I dont have access to your code but try if this format works(Since I havent tried this so I have my doubts if this will work or not).
public class SonyResult
{
public int ID { get; set; }
public string TYPE { get; set; }
public string TITLE { get; set; }
public string PRICE { get; set; }
public string IMAGE { get; set; }
}
public class WindowsResult
{
public int ID { get; set; }
public string TYPE { get; set; }
public string TITLE { get; set; }
public string PRICE { get; set; }
public string IMAGE { get; set; }
}
public class RootObject
{
public List<SonyResult> SonyResult { get; set; }
public int success { get; set; }
public List<WindowsResult> WindowsResult { get; set; }
}
I have a problem with parsing json.
The json data is here: http://beta.fmeserver.com/fmerest/engines/.json?token=0ccfa0400b2d760fa3519baf18a557edb118356e.
I created some classes with json2csharp, but search is null:
var url = "http://beta.fmeserver.com/fmerest/engines/.json?token=0ccfa0400b2d760fa3519baf18a557edb118356e";
WebClient client = new WebClient();
var json = client.DownloadString(url);
var search = JsonConvert.DeserializeObject<ServiceResponse>(json);
public class Engine
{
public int FMEBuildNumber { get; set; }
public string FMEHostName { get; set; }
public string FMEInstanceName { get; set; }
public int currentJobID { get; set; }
public int maxTransactionResultFailure { get; set; }
public int maxTransactionResultSuccess { get; set; }
public int resultFailureCount { get; set; }
public int resultSuccessCount { get; set; }
public int transactionPort { get; set; }
}
public class Engines
{
public List<Engine> engine { get; set; }
}
public class ServiceResponse
{
public string requestURI { get; set; }
public string token { get; set; }
public Engines engines { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class RootObject
{
[JsonProperty("serviceResponse")]
public ServiceResponse ServiceResponse { get; set; }
}
How about going dynamic way using Json.Net? (without using any class generated by http://json2csharp.com/)
var url = "http://beta.fmeserver.com/fmerest/engines/.json?token=0ccfa0400b2d760fa3519baf18a557edb118356e";
using (WebClient wc = new WebClient())
{
string json = wc.DownloadString(url);
dynamic dynobj = JsonConvert.DeserializeObject(json);
foreach (var engine in dynobj.serviceResponse.engines.engine)
{
Console.WriteLine("{0} {1}", engine.FMEInstanceName, engine.transactionPort);
}
}