deserialize json list from Rest server c# - c#

Just a little stuck here, I want to grab "notifications"(list) from the json that is sent back to me from the server. Please see below:
{"amountCashback": 0,"amountGratuity": 0, "amountTotal": 0, "notifications":["APPROVED" ],}
notifications being enum;
notifications {
string = ['APPROVED', 'BAD_SWIPE', 'CARD_ERROR', 'CARD_EXPIRED', 'CARD_NOT_SUPPORTED', 'CONNECTING', 'CONNECTION_MADE', 'DECLINED', 'DECLINED_BY_CARD', 'INSERT_CARD', 'PIN_ENTRY', 'PLEASE_WAIT', 'PRESENT_CARD', 'PRESENT_ONLY_ONE_CARD', 'PROCESSING_ERROR', 'REMOVE_CARD', 'RETRYING', 'REQUEST_SENT', 'RE_PRESENT_CARD', 'SIGNATURE_VERIFICATION', 'SIGNATURE_VERIFICATION_PROCESS_COMPLETED', 'SIGNATURE_VERIFICATION_PROCESS_COULD_NOT_BE_COMPLETED', 'SIGNATURE_VERIFICATION_IN_PROGRESS', 'SIGNATURE_VERIFICATION_TIMEOUT', 'TRANSACTION_FINISHED', 'TRANSACTION_STARTED']
Using json to c# I have created the class below
class Polling
{
public int amountBase { get; set; }
public int amountCashback { get; set; }
public int amountGratuity { get; set; }
public int amountTotal { get; set; }
public string authCode { get; set; }
public string cardSchemeName { get; set; }
public string cardHolderVerificationMethod { get; set; }
public string location { get; set; }
public List<string> notifications { get; set; }
public string paymentMethod { get; set; }
public string transactionResult { get; set; }
public DateTime transactionTime { get; set; }
public string transactionType { get; set; }
public string endPoint { get; set; }
public httpVerb httpMethod { get; set; }
public string userPassword { get; set; }
public int sendAmount { get; set; }
public string requestId { get; set; }}
I want to be able to deserialize and grab the notifications to display them on screen. Below I have added the code I am using for this.
try
{
response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseValue = reader.ReadToEnd();
}
if (response.StatusCode == HttpStatusCode.OK)
{
dynamic jsonObjtpi = JsonConvert.DeserializeObject(strResponseValue);
string notifications = jsonObjtpi.notifications.ToString();
return notifications;
}
}
}
}
Thanks guys, really appreciate it

Json can use your strongly typed Polling object, e.g.
Polling polling = JsonConvert.DeserializeObject<Polling>(strResponseValue);
See https://www.newtonsoft.com/json/help/html/DeserializeObject.htm

Related

C# JSON to each item

I'm trying to get some information from a JSON link and display it to the user in a friendly way. I'm tried everything and can't seem to get my head around this.Basically I want to show the user
ID = somevalue
GUID = SomeValue
Name = Somevalue
etc.
After I got my JSON I went to json2csharp and got my classes as shown below:
public class Computer
{
public string ID { get; set; }
public string GUID { get; set; }
public string name { get; set; }
public string type { get; set; }
public string entity { get; set; }
public string serial { get; set; }
public string uuid { get; set; }
public string inventorynumber { get; set; }
public string status { get; set; }
public string site { get; set; }
public string location { get; set; }
public string manufacturer { get; set; }
public string model { get; set; }
public string owner { get; set; }
public string lastuser { get; set; }
public string domain { get; set; }
public string os { get; set; }
public string servicepack { get; set; }
public string osversion { get; set; }
}
public class Data
{
public List<Computer> computers { get; set; }
}
public class RootObject
{
public string state { get; set; }
public Data data { get; set; }
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.xxx/?xxx=xxx&format=json ");
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
var rawJson = reader.ReadToEnd();
RootObject rootResult = JsonConvert.DeserializeObject<RootObject>(rawJson);
Console.Write();
Console.ReadKey();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
Console.WriteLine(errorText);
}
throw;
}
with this code if I do
Console.WriteLine(rootResult.state);
I get my "Success" value. But I can't find a way to actually get the data I have under "Computer"
Can anyone show me a way what I'm doing wrong?
I also tried to follow the similar questions but they all seem to be different since my JSON format is a little different.
Thanks in advance.
What happens if you simply iterate over your rootResult.data.computers, which should be a list of computers?
if(rootResult.data != null)
{
foreach (var computer in rootResult.data.computers)
{
Console.WriteLine(computer.ID);
Console.WriteLine(computer.GUID);
// etc for all properties
}
}

Response is null when I used Restsharp library's GET request to access Json data

I am using Restsharp library to do Webservice operations.I tried to access data from the link(http://www.mocky.io/v2/595616d92900003d02cd7191) and print it in Console but I am not getting any response.When I used breakpoints,Response is showing null.Here's my code to get data from the link.
private async void GetItemsFromJSON()
{
IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
IRestRequest request = new RestRequest(Method.GET);
request.RequestFormat = DataFormat.Json;
try
{
await Task.Run(() =>
{
IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
Console.WriteLine(response.Content);
}
public class ItemDetails
{
public List<Itemschema> items { get; set; }
}
public class Itemschema
{
public int id { get; set; }
public string sku { get; set; }
public string name { get; set; }
public int attribute_set_id { get; set; }
public int price { get; set; }
public int status { get; set; }
public int visibility { get; set; }
public string type_id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public int weight { get; set; }
}
Am I missing something here?My schema class which corresponds to the Json data is shown above.
I suspect that:
IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
should be:
IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
http://www.mocky.io/v2/595616d92900003d02cd7191 seems to return an items property which contains an array of schemas. That maps closer to ItemDetails than List<ItemDetails>.
This complete sample works, so you may want to compare it with your code:
using System;
using System.Collections.Generic;
using RestSharp;
namespace Test
{
public class ItemDetails
{
public List<Itemschema> items { get; set; }
}
public class Itemschema
{
public int id { get; set; }
public string sku { get; set; }
public string name { get; set; }
public int attribute_set_id { get; set; }
public int price { get; set; }
public int status { get; set; }
public int visibility { get; set; }
public string type_id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public int weight { get; set; }
}
public class Program
{
static void Main(string[] args)
{
IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
IRestRequest request = new RestRequest(Method.GET);
request.RequestFormat = DataFormat.Json;
IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
Console.WriteLine(Items.items.Count);
Console.ReadLine();
}
}
}

C# Beginner - Using classes in different from different classes

This is a file called TwitchAPIexample in folder Plugins under project MyFirstBot. The classes and code is below:
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace MyFirstBot.Plugins
{
public class TwitchAPIexample
{
private const string url = "https://api.twitch.tv/kraken/streams/<channel>";
public bool isTwitchLive;
private static void BuildConnect()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "Get";
request.Timeout = 12000;
request.ContentType = "application/json";
request.Headers.Add("authorization", "<token>");
using (System.IO.Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
RootObject r = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
}
}
}
public class Preview
{
public string small { get; set; }
public string medium { get; set; }
public string large { get; set; }
public string template { get; set; }
}
public class Channel
{
public bool mature { get; set; }
public string status { get; set; }
public string broadcaster_language { get; set; }
public string display_name { get; set; }
public string game { get; set; }
public string language { get; set; }
public int _id { get; set; }
public string name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public bool partner { get; set; }
public string logo { get; set; }
public string video_banner { get; set; }
public string profile_banner { get; set; }
public object profile_banner_background_color { get; set; }
public string url { get; set; }
public int views { get; set; }
public int followers { get; set; }
}
public class Stream
{
public long _id { get; set; }
public string game { get; set; }
public int viewers { get; set; }
public int video_height { get; set; }
public int average_fps { get; set; }
public int delay { get; set; }
public string created_at { get; set; }
public bool is_playlist { get; set; }
public Preview preview { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Stream stream { get; set; }
}
}
}
What I need to do is use the classes in the namespace MyfirstBot.Plugins in a different file under MyFirstBot project file. I have:
using namespace MyFirstBot.Plugins
but I'm not sure how to use the RootObject. I have tried using:
TwitchAPIexample.stream TwitchLive = new TwitchAPIexample.stream()
but I dont really know how to go from there to check the other strings in the JSON, set them equal to strings, basically just how to manipulate everything in the TwitchAPIexample class.
Again I'm a C# Noob so you don't have to write it for me, but if you could explain it or hit me up with a good resource. I have googled and still am confused. OOP isnt my strong suit.
This is as far as I have gotten:
namespace MyFirstBot
{
public class DiscordBot
{
DiscordClient client;
CommandService commands;
TwitchClient TwitchClient;
TwitchAPIexample.Stream TwitchLive = new TwitchAPIexample.Stream();
public DiscordBot()
{
if(TwitchLive.equals(null))
{
//stream is offline
}
}
}
}
I'm not sure this is the best method.
For me it looks like you need to change your architecture a bit. You don't need static method, and you need to create property trough which you'd be able to access RootObject. And you don't really need to nest those classes.
public class TwitchAPIexample
{
private const string url = "https://api.twitch.tv/kraken/streams/<channel>";
public bool IsTwitchLive { get; set; }
public RootObject Root { get; set; }
public TwitchAPIexample()
{
BuildConnect();
}
private void BuildConnect()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "Get";
request.Timeout = 12000;
request.ContentType = "application/json";
request.Headers.Add("authorization", "<token>");
using (System.IO.Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
this.Root = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
}
}
}
}
public class Preview
{
public string small { get; set; }
public string medium { get; set; }
public string large { get; set; }
public string template { get; set; }
}
public class Channel
{
public bool mature { get; set; }
public string status { get; set; }
public string broadcaster_language { get; set; }
public string display_name { get; set; }
public string game { get; set; }
public string language { get; set; }
public int _id { get; set; }
public string name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public bool partner { get; set; }
public string logo { get; set; }
public string video_banner { get; set; }
public string profile_banner { get; set; }
public object profile_banner_background_color { get; set; }
public string url { get; set; }
public int views { get; set; }
public int followers { get; set; }
}
public class Stream
{
public long _id { get; set; }
public string game { get; set; }
public int viewers { get; set; }
public int video_height { get; set; }
public int average_fps { get; set; }
public int delay { get; set; }
public string created_at { get; set; }
public bool is_playlist { get; set; }
public Preview preview { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Stream stream { get; set; }
}
Now you can do next
namespace MyFirstBot
{
public class DiscordBot
{
DiscordClient client;
CommandService commands;
TwitchClient TwitchClient;
TwitchAPIexample twitchLive = new TwitchAPIexample();
public DiscordBot()
{
if(twitchLive.Root == null || twitchLive.Root.Stream == null)
{
//stream is offline
}
}
}
}
So you are accessing the root object using the twitchLive.Root and trough the root you can access your stream twitchLive.Root.Stream

Unable To Parse JSON Response in C#

I am trying to parse a whois json response but when I try parse it I get null values.
string html;
string whoisUrl = "https://whois.apitruck.com/:google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(whoisUrl);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
html = reader.ReadToEnd();
}
}
Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.created);
Object
class Class1
{
public string created { get; set; }
}
can anyone please point what I am doing wrong here ?
Your Class1 doesn't get the value since "created" is part of the "response" and not the root level of the JSON reponse.
You'll either need to use dynamic or create a hierarchy for the classes for a simple fix.
class Class1
{
public Response Response { get; set; }
}
class Response
{
public string created { get; set; }
}
Then you can use this:
Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.Response.created);
UPDATE
Also, here's an example of how to use the dynamic:
var m = JsonConvert.DeserializeObject<dynamic>(html);
DateTime created = (DateTime)m.response.created;
There is nice app to convert json to .net class:
public class Registrar
{
public string id { get; set; }
public string name { get; set; }
public object email { get; set; }
public string url { get; set; }
}
public class Response
{
public string name { get; set; }
public string idnName { get; set; }
public List<string> status { get; set; }
public List<string> nameserver { get; set; }
public object ips { get; set; }
public string created { get; set; }
public string changed { get; set; }
public string expires { get; set; }
public bool registered { get; set; }
public bool dnssec { get; set; }
public string whoisserver { get; set; }
public List<object> contacts { get; set; }
public Registrar registrar { get; set; }
public List<string> rawdata { get; set; }
public object network { get; set; }
public object exception { get; set; }
public bool parsedContacts { get; set; }
}
public class RootObject
{
public int error { get; set; }
public Response response { get; set; }
}
...
RootObject result = JsonConvert.DeserializeObject<RootObject>(html);
var created = result.response.created;

Navigating JSON data in c#

I'm trying to check if a twitch.tv stream is online or not via c#. Currently I have:
private bool checkStream(String chan)
{
using (var w = new WebClient()) {
String json_data = w.DownloadString("https://api.twitch.tv/kraken/streams/" + chan);
JObject stream = JObject.Parse(json_data);
print(json_data); //just for testing purposes
if (stream["stream"] != null)
{
print("YIPPEE");
}
}
return false;
}
Here's the twitch JSON API for what I'm downloading: https://github.com/justintv/Twitch-API/blob/master/v2_resources/streams.md#get-streamschannel
As you can see, if a stream is currently offline, the stream field just says null. But obviously, it's still there, so my if(stream["stream"]!=null) check doesn't work. Never used JSON or Newtonsoft's json.net before, so I'm kind of at a loss for what to do. Thanks in advance for any help!
You need to create a class that you can de-serialize the json to. For instance, if you receive json that looks like this
MyJson = {
Prop1 : "Property1",
Prop2 : "Property2"
}
then you'll need to create a class that acts as a contract between your program and the JSON stream.
public class MyJsonClass{
public string Prop1;
public string Prop2;
public MyJsonClass(){
}
}
Now, you can deserialize the json to your C# class and check it for any null values:
// Create a MyJson class instance by deserializing your json string
string myJsonString = ...//get your json string
MyJsonClass deserialized = JsonConvert.DeserializeObject<MyJsonClass>(myJsonString);
if ( deserialized.Prop1 == null )
//etc etc etc
Here's a full processor for that Json response (Disclaimer: I used http://json2csharp.com/ for this code ) :
public class Links
{
public string channel { get; set; }
public string self { get; set; }
}
public class Links2
{
public string self { get; set; }
}
public class Links3
{
public string stream_key { get; set; }
public string editors { get; set; }
public string subscriptions { get; set; }
public string commercial { get; set; }
public string videos { get; set; }
public string follows { get; set; }
public string self { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public string display_name { get; set; }
public Links3 _links { get; set; }
public List<object> teams { get; set; }
public string status { get; set; }
public string created_at { get; set; }
public string logo { get; set; }
public string updated_at { get; set; }
public object mature { get; set; }
public object video_banner { get; set; }
public int _id { get; set; }
public string background { get; set; }
public string banner { get; set; }
public string name { get; set; }
public string url { get; set; }
public string game { get; set; }
}
public class Stream
{
public Links2 _links { get; set; }
public string broadcaster { get; set; }
public string preview { get; set; }
public long _id { get; set; }
public int viewers { get; set; }
public Channel channel { get; set; }
public string name { get; set; }
public string game { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public Stream stream { get; set; }
}
and here's how to use it :
bool StreamOnline = false;
using (var w = new WebClient())
{
var jsonData = w.DownloadData("https://api.twitch.tv/kraken/streams/" + + chan);
var s = new DataContractJsonSerializer(typeof(RootObject));
using (var ms = new MemoryStream(jsonData))
{
var obj = (RootObject)s.ReadObject(ms);
StreamOnline = obj.stream == null;
}
}
return StreamOnline;
Please note that you need to reference System.Runtime.Serialization and add using System.Runtime.Serialization.Json; to use DataContractJsonSerializer. If you don't need every detail just make the stream property of type object (in the RootObject class) and check whether it's null or not.
Have you tried this. The HasValues is a bool property that checks if there are child tokens, if its value is null there will not be any child tokens.
if (stream["stream"].HasValues)
{
print("YIPPEE");
}else
{
print("No Stream");
}

Categories