JSON deserialize output to Textbox - c#

First time working with JSON and trying to figure this one out. I am able to connect to the API and get the JSON string to display in my textbox. I am confused on how to properly display the data correctly in the textbox.
This my code I have.
{
GetReportList p = new GetReportList();
var client = new RestClient(p.WebReportList);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "Value");
var thisJsonStr = "{\"Credentials\": { \"ApiKey\": \"xxxxxxxx\",\"MerchantID\": \"xxxxxxx\",\"StoreID\":\"xxxxx\",\"Username\": \"xxxxx\",\"Password\": \"xxxx\"},\"ReportID\": [\"34\"]}";
request.AddParameter("application/json", thisJsonStr, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
deseiralizeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Report>(response.Content);
ReportListbx.Text = (response.Content);
}
My output looks like this when I debug it.
{"Result":"OK","Reports":[{"ReportID":"18","Name":"END OF DAY","Type":"group"},{"ReportID":"34","Name":"MANDY REPORT","Type":"group"},{"ReportID":"17","Name":"Lottery Paid Out","Type":"preset"}
My output i want it to be the "ReportID","name", Type"
Thanks
#Saeed Aghdam
I have edited the code to this
request.AddParameter("application/json", thisJsonStr, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var json = response.Content;
var deseiralizeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Report>(json);
foreach (var report in deseiralizeObject.Reports)
ReportListbx.Text = ($"{report.ReportID} - {report.Name} - {report.Type}");
And I get the last record from the JSON data.

I write a very simple console application, in this app, it gets your provided sample JSON and deserializes it to a class. so you can iterate items (elements) and display them.
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
public class Report
{
public string Result { get; set; }
public IEnumerable<ReportItem> Reports { get; set; }
}
public class ReportItem
{
public string ReportID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
class Program
{
static void Main(string[] args)
{
var json = #"{""Result"":""OK"",""Reports"":[{""ReportID"":""18"",""Name"":""END OF DAY"",""Type"":""group""},{""ReportID"":""34"",""Name"":""MANDY REPORT"",""Type"":""group""},{""ReportID"":""17"",""Name"":""Lottery Paid Out"",""Type"":""preset""}]}";
var deseiralizeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Report>(json);
foreach(var report in deseiralizeObject.Reports)
Console.WriteLine($"{report.ReportID} - {report.Name} - {report.Type}");
Console.ReadKey();
}
}
}
Edit: An alternative for the above method is using a dynamic object, the following code do the same as the above codes are doing:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
public class Report
{
public string Result { get; set; }
public IEnumerable<ReportItem> Reports { get; set; }
}
public class ReportItem
{
public string ReportID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
class Program
{
static void Main(string[] args)
{
var json = #"{""Result"":""OK"",""Reports"":[{""ReportID"":""18"",""Name"":""END OF DAY"",""Type"":""group""},{""ReportID"":""34"",""Name"":""MANDY REPORT"",""Type"":""group""},{""ReportID"":""17"",""Name"":""Lottery Paid Out"",""Type"":""preset""}]}";
dynamic d = JObject.Parse(json);
foreach (var report in d.Reports)
Console.WriteLine($"{report.ReportID} - {report.Name} - {report.Type}");
Console.ReadKey();
}
}
}
Screenshot:

Related

How do I call JSON in a simplified manner

I am connecting to an external API which seems to be returning JSON
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
}
When I move over .Data.Balances, it shows:
IEnumerable<API.Net.Objects.Spot.SpotData.APIBalance>
API.Net.Objects.Spot.SpotData.APIAccountInfo.Balances { get; set; }
List of assets and their current balances
Here is an extract of the JSON data:
"balances":[
{
"asset":"ABC",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"DEF",
"free":"0.00000000",
"locked":"0.00000000"
},
{
"asset":"GHI",
"free":"0.00000000",
"locked":"0.00000000"
}
]
How do I make use of this data so if I type console.writeline(data[0]["asset"]), it gives me ABC?
This seems to be the simplist solution:
using System.Linq;
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances.ToList();
Console.WriteLine(data[0].asset);
Console.WriteLine(data[0].free);
Console.WriteLine(data[0].locked);
}
Hy,
From the sample file you can create a class ´balance »
Public class balance
{
Public string asset {get; set;}
Public Free .......
Public Locked .....
}
And then you can use Json.net
To deserialize the JSon file
public void serializejson()
{
List balances = JsonConvert.DeserializeObject<List>(data);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Game
{
public class Balance
{
[JsonPropertyName("asset")]
public string Asset { get; set; }
[JsonPropertyName("free")]
public string Free { get; set; }
[JsonPropertyName("locked")]
public string Locked { get; set; }
}
public class Root
{
[JsonPropertyName("balances")]
public List<Balance> Balances { get; set; }
}
class Program
{
static void Main(string[] args)
{
var data = File.ReadAllText("test.json");
var deserialized = JsonSerializer.Deserialize<Root>(data);
var balances = deserialized.Balances;
// Don't iterati in such a way! Use foreach instead.
for (int i = 0; i < balances.Count; i++)
{
Console.WriteLine($"{balances[i].Asset} {balances[i].Free} {balances[i].Locked}");
}
foreach (var balance in balances)
{
Console.WriteLine($"{balance.Asset} {balance.Free} {balance.Locked}");
}
}
}
}
You can use this code for you:
public class Balance {
public string asset { get; set; }
public string free { get; set; }
public string locked { get; set; }
}
public class Root {
public List<Balance> balances { get; set; }
}
And for deserialize:
using (var client = new APIClient())
{
var data = client.General.GetAccountInfo().Data.Balances;
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(data);
Console.WriteLine(myDeserializedClass.balances[0].asset);
}

How do I use NewsApi.org in my UWP Project?

I'm using C# and UWP xml to create a news feed. Like a phone news widget but for the computer. I came across https://newsapi.org/ and thought it was interesting. But I don't know how to implement and there isn't any tutorials on C# for this api website. How do I use this and how do I show the article.Title, article.Author, and article.Description on 3 textblocks I created?
edit: I found a video for c# but it is for console.writeline, not a xaml front page.
So what I did was create a new class.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NewsAPI;
using NewsAPI.Models;
using NewsAPI.Constants;
using System.Net.Http;
using Newtonsoft.Json;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
namespace news
{
public class newsapi
{
HttpClient client = new HttpClient();
//public static async void Main(string[] args)
//{
// newsapi program = new newsapi();
// await program.GetArticles();
//}
//public async Task GetArticles()
//{
// string response = await client.GetStringAsync("https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=06112b69bb054cfeb70bbf188873f98e");
// NewsResponse newsObject = JsonConvert.DeserializeObject<NewsResponse>(response);
//}
public async static Task<Article> GetArticlesMain()
{
var http = new HttpClient();
var response = await http.GetAsync("https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=06112b69bb054cfeb70bbf188873f98e");
var result = await response.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(Article));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (Article)serializer.ReadObject(ms);
return data;
}
[DataContract]
public class NewsResponse
{
[DataMember]
public string status { get; set; }
[DataMember]
public int totalResults { get; set; }
[DataMember]
public List<Article> Articles { get; set; }
}
[DataContract]
public class Article
{
[DataMember]
public string Title { get; set; }
}
}
}
and tried to get the title of the news api in my mainpage.xaml in a textblock in a page_loaded event:
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
//RootObject myWeather = await OpenWeather.GetWeather(20, 30);
Article article = await newsapi.GetArticlesMain();
tbContent.Text = article.Title;
}
But the textblock doesn't show anything and an exception user-unhandled was thrown in "tbContent.Text = article.Title" this line saying "Value cannot be null". So what is going on and how to fix it?
When you get the Json string from the network, if you want to convert to a type, you need to provide a class corresponding to the json structure.
var serializer = new DataContractJsonSerializer(typeof(Article));
Here is the main problem, the obtained json string should be of type NewsResponse, so it should be like this:
var serializer = new DataContractJsonSerializer(typeof(Article));
This is a complete process:
News.cs
public class NewsApi
{
public async static Task<List<Article>> GetArticlesMain()
{
var http = new HttpClient();
var response = await http.GetAsync("your_news_url");
var result = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<NewsResponse>(result);
return data.articles;
}
}
public class NewsResponse
{
public string status { get; set; }
public int totalResults { get; set; }
public List<Article> articles { get; set; }
}
public class Article
{
public Source source { get; set; }
public string author { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public string urlToImage { get; set; }
public DateTime publishedAt { get; set; }
public string content { get; set; }
}
public class Source
{
public string id { get; set; }
public string name { get; set; }
}
News.xaml.cs
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
List<Article> articles = await NewsApi.GetArticlesMain();
tbContent.Text = articles.First().title;
}

With RestSharp, Newtonsoft.Json Cannot deserialize the current JSON array (e.g. [1,2,3])

I am new to C# API... I created a new server using nodejs server get data from SQL server to generate json and I am creating a custom application using c# windows application using RestSharp sent a request to a server and received a response using Newtonsoft I got error cannot deserialize current json array help me to solve the problem below code
JSON
[[{"id":2000,"engine":1,"wheel":1,"ac":1,"nitro":1,"rim":1},{"id":2001,"engine":1,"wheel":1,"ac":1,"nitro":1,"rim":1}]]
Code
using RestSharp;
using Newtonsoft.Json;
private void Form1_Load(object sender, EventArgs e)
{
var client = new RestClient("http://localhost:8000/employees");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var x = JsonConvert.DeserializeObject<RootObject>(response.Content);
foreach (var player in x.Abbrecipes)
{
comboBox1.Items.Add(player.id);
}
}
public class Abbrecipe
{
public int id { get; set; }
public int engine { get; set; }
public int wheel { get; set; }
public int ac { get; set; }
public int nitro { get; set; }
public int rim { get; set; }
}
public class RootObject
{
public List<Abbrecipe> Abbrecipes { get; set; }
}
here is the code for your current situation as a method using WebClient instead of RestClient:
private static Rootobject publicFeed;
public static void Set()
{
publicFeed = new Rootobject();
using (var client = new WebClient())
{
string result;
try
{
result = client.DownloadString("your json");//configure json stringdata
}
catch (Exception)
{
Console.WriteLine("This application needs a valid internet connection, please try again.");
result = null;
return;
}
publicFeed = JsonConvert.DeserializeObject<Rootobject>(result);
}
}

How to get JSON result into List

I have my own code here and already get the JSON result then I haven't idea to move the JSON result into the interface (IEntities function) list below.
class GetCategory : IEntities
{
private JsonHandle _jsonhandle;
private string _ocategory;
public async void TaskCategory()
{
_jsonhandle = new JsonHandle();
_jsonhandle.StrAPI = "http://api.nytimes.com/svc/books/v3/lists/names.json?api-key=7bb034b7693d6f9753b2f68e00b98c78%3A16%3A73599437";
var client = new HttpClient();
Task<string> datatask = client.GetStringAsync(_jsonhandle.StrAPI);
try
{
var JsonRead = await datatask;
JObject oCategory = JObject.Parse(JsonRead);
List<JToken> results = oCategory["results"].Children().ToList();
//serialize JSON results into .NET objects
List<object> dtCategory = new List<object>();
foreach (JToken result in results)
{
object _dtcategory = JsonConvert.DeserializeObject<object>(result.ToString());
dtCategory.Add(_dtcategory);
var listname = result["list_name"];
}
}
catch (Exception error)
{
Console.WriteLine("AW!" + error.StackTrace);
}
public List<object> BookCategory()
{
}
}
In the last function that in IEntities interface, I need to put my JSON result in interface List<object>.
When working with JSON, the first thing to do is creating a model object. In order to this, either you should analyze JSON output manually, or you can generate the model automatically by going to the following link and pasting either the JSON your are going to use or the service link;
json2csharp.com
I've just used your API link and the output generated is;
public class Result
{
public string list_name { get; set; }
public string display_name { get; set; }
public string list_name_encoded { get; set; }
public string oldest_published_date { get; set; }
public string newest_published_date { get; set; }
public string updated { get; set; }
}
public class RootObject
{
public string status { get; set; }
public string copyright { get; set; }
public int num_results { get; set; }
public List<Result> results { get; set; }
}
This will be our model.
Secondly, as far as I can see, what you want to do is only to get the result list, thus, as you deserialize the JSON output, you are going to use the Model.Result and move them into a list.
Then, to get the response, a private method can be used which that returns an async Task<string>, and on the BookCategory() method, you can get the Results and deserialize JSON and initialize a list based on your JSON object model;
public List<Model.Result> BookCategory()
{
List<Model.Result> list = new List<Model.Result>();
var model = JsonConvert.DeserializeObject<Model.RootObject>(TaskCategory().Result);
list = model.results;
return list;
}
Deserializing JSON is as simply as below;
var model = JsonConvert.DeserializeObject<Model.RootObject>(TaskCategory().Result);
Model.cs
using System.Collections.Generic;
namespace SO1
{
public class Model
{
public class Result
{
public string list_name { get; set; }
public string display_name { get; set; }
public string list_name_encoded { get; set; }
public string oldest_published_date { get; set; }
public string newest_published_date { get; set; }
public string updated { get; set; }
}
public class RootObject
{
public string status { get; set; }
public string copyright { get; set; }
public int num_results { get; set; }
public List<Result> results { get; set; }
}
}
}
GetCategory.cs
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
using System;
namespace SO1
{
public class GetCategory : IEntities
{
private String BaseUri;
public GetCategory(string BaseUri)
{
this.BaseUri = BaseUri;
}
private async Task<string> TaskCategory()
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = "text";
var response = await httpClient.GetStringAsync(BaseUri);
return response;
}
public List<Model.Result> BookCategory()
{
List<Model.Result> list = new List<Model.Result>();
var model = JsonConvert.DeserializeObject<Model.RootObject>(TaskCategory().Result);
list = model.results;
return list;
}
}
}
IEntities
using System.Collections.Generic;
namespace SO1
{
public interface IEntities
{
List<Model.Result> BookCategory();
}
}
Program.cs
using System;
using System.Collections.Generic;
namespace SO1
{
class Program
{
static void Main(string[] args)
{
string BaseUri = "http://api.nytimes.com/svc/books/v3/lists/names.json?api-key=7bb034b7693d6f9753b2f68e00b98c78%3A16%3A73599437";
IEntities entity = new GetCategory(BaseUri);
List<Model.Result> listBookCategory = new List<Model.Result>();
listBookCategory = entity.BookCategory();
foreach (Model.Result r in listBookCategory)
{
Console.WriteLine();
Console.WriteLine("...List Name : " + r.list_name);
Console.WriteLine("...Display Name : " + r.display_name);
Console.WriteLine("...List Name Encoded : " + r.list_name_encoded);
Console.WriteLine("...Oldest Published Date : " + r.oldest_published_date);
Console.WriteLine("...Oldest Published Date : " + r.newest_published_date);
Console.WriteLine("...Updated : " + r.updated);
Console.WriteLine();
}
}
}
}
Output (only first three results printed)
...List Name : Combined Print and E-Book Fiction
...Display Name : Combined Print & E-Book Fiction
...List Name Encoded : combined-print-and-e-book-fiction
...Oldest Published Date : 2011-02-13
...Oldest Published Date : 2015-12-27
...Updated : WEEKLY
...List Name : Combined Print and E-Book Nonfiction
...Display Name : Combined Print & E-Book Nonfiction
...List Name Encoded : combined-print-and-e-book-nonfiction
...Oldest Published Date : 2011-02-13
...Oldest Published Date : 2015-12-27
...Updated : WEEKLY
...List Name : Hardcover Fiction
...Display Name : Hardcover Fiction
...List Name Encoded : hardcover-fiction
...Oldest Published Date : 2008-06-08
...Oldest Published Date : 2015-12-27
...Updated : WEEKLY

C# Json and HttpWebRequest

I used HttpWebRequest to get the content from a website.
The problem is that I got a response in json and I don't really know how to use, convert and implement that data in my program.
Current code:
namespace Web_Scraper
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string final_response = stream.ReadToEnd();
Console.WriteLine("Genuine Purity Fist");
Console.WriteLine(final_response);
Console.ReadKey();
}
}
}
Response:
{"success":true,"lowest_price":"1,05\u20ac","volume":"26","median_price":"1,06\u20ac"}
json2csharp code:
public class RootObject
{
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
Hey you could downloade Json.NET and parse your json string like this:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
var final_response = stream.ReadToEnd();
// Converts the unicode to string correctValue.
string correctValue = "Euro";
StringBuilder sb = new StringBuilder(final_response);
if (sb.ToString().Contains("\\u20ac"))
{
sb.Replace("\\u20ac", correctValue);
}
dynamic items = JObject.Parse(sb.ToString());
bool success = items.success;
string lowest = items.lowest_price;
string volume = items.volume;
string median = items.median_price;
// Create a test object of RootObject class and display it's values in cw.
RootObject r = new RootObject(success, lowest, volume, median);
Console.WriteLine("TEST OBJECT VALUES: Success: " + r.success + ", lPrice: " + r.lowest_price + ", vol: " + r.volume + ", mPrice: " + r.median_price + "\n");
// Calculation example
double num1 = Convert.ToDouble(r.FixComma(r.lowest_price,correctValue));
double num2 = Convert.ToDouble(r.FixComma(r.median_price, correctValue));
double result = num1 + num2;
Console.WriteLine("Result: " + result+"\n");
Console.WriteLine("Genuine Purity Fist");
Console.WriteLine(final_response);
Console.ReadKey();
}
}
public class RootObject
{
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
public RootObject(bool success, string lowest_price, string volume, string median_price)
{
this.success = success;
this.lowest_price = lowest_price;
this.volume = volume;
this.median_price = median_price;
}
public string FixComma(string value,string currency)
{
string correctValue = ".";
string correctValue2 = "";
StringBuilder sb = new StringBuilder(value);
if (sb.ToString().Contains(","))
{
sb.Replace(",", correctValue);
}
if (sb.ToString().Contains(currency))
{
sb.Replace(currency, correctValue2);
}
return sb.ToString();
}
}
}
Here is a link that explains how to downloade Json.NET https://www.nuget.org/packages/newtonsoft.json/.
One option is to use the JavaScriptSerializer class in the System.Web.Script.Serialization namespace.
For example:
RootObject obj = new JavaScriptSerializer().Deserialize<RootObject>(final_response);
Other options might be:
Do it yourself using reflection or manual parsing.
Third-party libraries like this one.
I would use JSON.NET for this. It provides a powerful and flexible way to deserialize and consume the data (and lets you change your mind about how to do it fairly easily later). It's also available as a NuGet package.
The simplest way would be to deserialize it into a dynamic or Object instance:
var object = JsonConvert.Deserialize<Object>(final_response);
var isSuccessful = object.success; // true or false
// ...
(You can replace object with dynamic too.)
If you want to deserialize to a class, create one:
class PriceData {
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
Then call .Deserialize<PriceData>(final_response) instead.
If you don't like lowercase-named or underscore-named variables (which is not the common style in C#), you can override the deserialization to specify which field to use for which C# property:
class PriceData {
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("lowest_price")]
public string LowestPrice { get; set; }
[JsonProperty("volume")]
public string Volume { get; set; }
[JsonProperty("median_price")]
public string MedianPrice { get; set; }
}

Categories

Resources