Navigating JSON data in c# - 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");
}

Related

ASP.NET C# Deserialized Json Object

I have json like this
{
"reader_name":"FX9600EAF871",
"mac_address":"84:24:8D:FC:0E:AD",
"tag_reads":[
{
"epc":"E28068100000003C0A05E3B7",
"antennaPort":"1",
"peakRssi":"-31",
"seenCount":"2458",
"timeStamp":"14/02/2022 22:50:24:356",
"channelIndex":"5"
}
]
}
I try using this code
public class TagRead
{
public string epc { get; set; }
public string pc { get; set; }
public string antennaPort { get; set; }
public string peakRssi { get; set; }
public string seenCount { get; set; }
public string timeStamp { get; set; }
public string phase { get; set; }
public string channelIndex { get; set; }
public string isHeartBeat { get; set; }
}
public class Hdr
{
public string reader_name { get; set; }
public string mac_address { get; set; }
public List<TagRead> tag_reads { get; set; }
}
var deserialized = Newtonsoft.Json.JsonConvert.DeserializeObject<Hdr>(json);
When try to print reader name using
deserialized.reader_name
it gets result FX9600EAF87
but when print
deserialized.tag_reads
it get nothing?
my question is How to get epc & antennaport data?
thank you
Because deserialized.tag_reads is a collection instead of base type or string, you might get the result that you didn't want to get.
How to get epc & antennaport data?
you might try to use deserialized.tag_reads with foreach to iterator the collection then do your logic
var deserialized = Newtonsoft.Json.JsonConvert.DeserializeObject<Hdr>(json);
foreach(var item in deserialized.tag_reads){
//item.epc
//item.antennaPort
}
c# online

Convert Rest API JSON Response into C# object

I have a code REST API response which is json, and parsing to JObject and pulling a value from it. But i am getting the error when parsing to JObject.
Error: "Unexpected character encountered while parsing value: S. Path '', line 0, position 0."
Is there any other way to convert Json string to C# object.
I have the following code:
using Newtonsoft.Json;
using (HttpResponseMessage message = httpclient.GetAsync(folderIdURL).Result)
{
if(message.IsSuccessStatusCode)
{
var dataobjects = message.Content.ReadAsStringAsync();
//dataobjects = "{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/","title":"DQL query results","author":[{"name":"EMC Documentum"}],"updated":"2019-05-02T15:19:52.508+00:00","page":1,"items-per-page":100,"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)"}],"entries":[{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)&index=0","title":"0b0111738011c114","updated":"2019-05-02T15:19:52.508+00:00","published":"2019-05-02T15:19:52.508+00:00","links":[{"rel":"edit","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c114"}],"content":{"json-root":"query-result","definition":"https://gbc-dev5.cloud.wc.com/DctmRest/repositori es/dmgbsap_crt/types/dm_sysobject","properties":{"r_object_id":"0b0111738011c114","object_name":"04"},"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c114"}]}},{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)&index=1","title":"0b0111738011c115","updated":"2019-05-02T15:19:52.509+00:00","published":"2019-05-02T15:19:52.509+00:00","links":[{"rel":"edit","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c115"}],"content":{"json-root":"query-result","definition":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/types/dm_sysobject","properties":{"r_object_id":"0b0111738011c115","object_name":"05"},"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c115"}]}}]}"
JObject responseObj = JObject.Parse(dataobjects.ToString());
String id = (String)responseObj["entries" -->"content"-->"properties"-->"object_name"];
}
}
}
I am expecting the value from (String)responseObject["enteries"]["content"][" properties"]["object_name"]
JObjects are a pain. You could get a sample of the JSON response and paste it into a converter like json2csharp.com. It will generate a class for you which you can then use like so:
Generated Class:
public class MyClass
{
public string SomeProperty { get; set; }
public string AnotherProperty { get; set; }
}
Usage:
if (message.IsSuccessStatusCode)
{
var deserializedObject = JsonConvert.DeserializeObject<MyClass>(response.Content.ReadAsStringAsync().Result);
Console.WriteLine(deserializedObject.SomeProperty);
}
I would suggest to follow those steps:
You need to check that your json is actually a json, because an error says it is not. You can use online tools like this
If possible, avoid JObject and generate real classes. It is not that hard if you know the structure, and you can use another online tools
Modify your code to use classes
so you will have something like:
using System;
using Newtonsoft.Json;
namespace ConsoleApp11
{
class Program
{
public class Message
{
public Enteries enteries { get; set; }
}
public class Enteries
{
public Content content { get; set; }
}
public class Content
{
public Properties properties { get; set; }
}
public class Properties
{
public string object_name { get; set; }
}
static void Main(string[] args)
{
var input = "{\"enteries\":{\"content\":{ \"properties\":{ \"object_name\":\"your value string\"}}}}";
Message msg = JsonConvert.DeserializeObject<Message>(input);
Console.WriteLine(msg?.enteries?.content?.properties?.object_name ?? "no value");
Console.ReadKey();
}
}
}
I hope it helps 😊
Thank you so much for all the help and trips. Finally i am able to get the required value from JSON string.
Here is the Final code json2csharp.com
public class Author
{
public string name { get; set; }
}
public class Link
{
public string rel { get; set; }
public string href { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string href { get; set; }
}
public class Properties
{
public string r_object_id { get; set; }
public string object_name { get; set; }
}
public class Link3
{
public string rel { get; set; }
public string href { get; set; }
}
public class Content
{
public string json_root { get; set; }
public string definition { get; set; }
public Properties properties { get; set; }
public List<Link3> links { get; set; }
}
public class Entry
{
public string id { get; set; }
public string title { get; set; }
public DateTime updated { get; set; }
public DateTime published { get; set; }
public List<Link2> links { get; set; }
public Content content { get; set; }
}
public class RootObject
{
public string id { get; set; }
public string title { get; set; }
public List<Author> author { get; set; }
public DateTime updated { get; set; }
public int page { get; set; }
public int items_per_page { get; set; }
public List<Link> links { get; set; }
public List<Entry> entries { get; set; }
}
Using Newtonsoft.Json
First get the list of entries from the responseObj. Then loop each entries and use LINQ to JSON to get values by property name or index.
You can use Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want
JObject responseObj = JObject.Parse(dataobjects.ToString());
// get JSON result objects into a list
IList<JToken> entries = responseObj ["entries"].Children().ToList();
foreach(JToken entry in entries)
{
string object_name = (string) entry["content"]["properties"]["object_name"];
}

Trying to Export data in mongodb but got this Error ?Expected a nested document representing

Expected a nested document representing the serialized form of a Rootobject value, but found a value of type Array instead?
C# Code:
My guess is that I should write a custom serializer for that class but I couldn't find any useful example in the MONGODB .NET DRIVER Manual.
I'm working with C# MongoDB driver
string inputFileName = #"1546346582.07002.json"; // initialize to the input file
IMongoCollection<Rootobject> coll = database.GetCollection<Rootobject>("BB");
using (var streamReader = new StreamReader(inputFileName))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
using (var jsonReader = new MongoDB.Bson.IO.JsonReader(line))
{
var context = BsonDeserializationContext.CreateRoot(jsonReader);
var document = coll.DocumentSerializer.Deserialize(context);
coll.InsertOne(document);
}
}
}
public class Rootobject
{
[BsonElement ("Property1")]
public Class1[] Property1 { get; set; }
}
public class Class1
{
[BsonId]
public ObjectId _id { get; set; }
[BsonElement ("ID")]
public string account { get; set; }
[BsonElement ("Account")]
public string accuser { get; set; }
[BsonElement ("Accuser")]
public string bookedby { get; set; }
[BsonElement ("BookedBy")]
public bool changed { get; set; }
[BsonElement ("Changed")]
}
public class Fromtovia
{
public string info { get; set; }
[BsonElement ("Info")]
public string address { get; set; }
[BsonElement("Address")]
public float lat { get; set; }
[BsonElement("Latitude")]
public float lon { get; set; }
[BsonElement("longitude")]
public string postcode { get; set; }
}
But I couldn't find anything Useful.

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;

C# JSON Object wont deserialize

So I have been able to get JSON objects for a few things, however this object is quite a bit more complex.
I'm trying to get comments from Reddit.
Here is the method I use:
public async Task<List<string>> GetComments(string currentSubreddit, string topicID)
{
string commentUrl = "http://www.reddit.com/r/" + currentSubreddit + "/comments/" + topicID + "/.json";
List<Comments> commentList = new List<Comments>();
string jsonText = await wc.GetJsonText(commentUrl);
Comments.RootObject deserializeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Comments.RootObject>(jsonText);
List<string> commentListTest = new List<string>();
//List<string> commentListTest = deserializeObject.data.children[0].data.children;
return commentListTest;
}
This is the GetJsonText method:
public async Task<string> GetJsonText(string url)
{
var request = WebRequest.Create(url);
string text;
request.ContentType = "application/json; charset=utf-8";
var response = (HttpWebResponse)await request.GetResponseAsync();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
return text;
}
And here is a link to the Object: http://pastebin.com/WQ8XXGNA
And a link to the jsonText: http://pastebin.com/7Kh6cA9a
The error returned says this:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in mscorlib.dll but was not handled in user code
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'JuicyReddit.Comments+RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
I'd appreciate if anybody could help me with figuring out whats wrong with this.
Thanks
There are a few problems with your code actually
public async Task<List<string>> GetComments(string currentSubreddit, string topicID)
You don't need to return a list of string here, u need to return a full object
First rename RootObject in the model to an appropriate name such as "CommentsObject"
So set up your class like so and name it CommentsObject.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YOURNAMESPACE.Comments
{
public class MediaEmbed
{
}
public class SecureMediaEmbed
{
}
public class Data4
{
public int count { get; set; }
public string parent_id { get; set; }
public List<string> children { get; set; }
public string name { get; set; }
public string id { get; set; }
public string subreddit_id { get; set; }
public object banned_by { get; set; }
public string subreddit { get; set; }
public object likes { get; set; }
public object replies { get; set; }
public bool? saved { get; set; }
public int? gilded { get; set; }
public string author { get; set; }
public object approved_by { get; set; }
public string body { get; set; }
public object edited { get; set; }
public object author_flair_css_class { get; set; }
public int? downs { get; set; }
public string body_html { get; set; }
public string link_id { get; set; }
public bool? score_hidden { get; set; }
public double? created { get; set; }
public object author_flair_text { get; set; }
public double? created_utc { get; set; }
public object distinguished { get; set; }
public object num_reports { get; set; }
public int? ups { get; set; }
}
public class Child2
{
public string kind { get; set; }
public Data4 data { get; set; }
}
public class Data3
{
public string modhash { get; set; }
public List<Child2> children { get; set; }
public object after { get; set; }
public object before { get; set; }
}
public class Replies
{
public string kind { get; set; }
public Data3 data { get; set; }
}
public class Data2
{
public string domain { get; set; }
public object banned_by { get; set; }
public MediaEmbed media_embed { get; set; }
public string subreddit { get; set; }
public object selftext_html { get; set; }
public string selftext { get; set; }
public object likes { get; set; }
public object secure_media { get; set; }
public object link_flair_text { get; set; }
public string id { get; set; }
public SecureMediaEmbed secure_media_embed { get; set; }
public bool clicked { get; set; }
public bool stickied { get; set; }
public string author { get; set; }
public object media { get; set; }
public int score { get; set; }
public object approved_by { get; set; }
public bool over_18 { get; set; }
public bool hidden { get; set; }
public string thumbnail { get; set; }
public string subreddit_id { get; set; }
public object edited { get; set; }
public object link_flair_css_class { get; set; }
public object author_flair_css_class { get; set; }
public int downs { get; set; }
public bool saved { get; set; }
public bool is_self { get; set; }
public string permalink { get; set; }
public string name { get; set; }
public double created { get; set; }
public string url { get; set; }
public object author_flair_text { get; set; }
public string title { get; set; }
public double created_utc { get; set; }
public int ups { get; set; }
public int num_comments { get; set; }
public bool visited { get; set; }
public object num_reports { get; set; }
public object distinguished { get; set; }
public Replies replies { get; set; }
public int? gilded { get; set; }
public string parent_id { get; set; }
public string body { get; set; }
public string body_html { get; set; }
public string link_id { get; set; }
public bool? score_hidden { get; set; }
public int? count { get; set; }
public List<string> children { get; set; }
}
public class Child
{
public string kind { get; set; }
public Data2 data { get; set; }
}
public class Data
{
public string modhash { get; set; }
public List<Child> children { get; set; }
public object after { get; set; }
public object before { get; set; }
}
public class CommentsObject
{
public string kind { get; set; }
public Data data { get; set; }
}
}
Make your namespace correct!
Then handle the request and deserialise into a list of commentobjects: (u can use the webclient instead of httpclient if you want, this is just an example)
private HttpClient client;
public async Task<List<CommentsObject>> GetComments()
{
client = new HttpClient();
var response = await client.GetAsync("http://www.reddit.com/r/AskReddit/comments/1ut6xc.json");
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
List<CommentsObject> comments = await JsonConvert.DeserializeObjectAsync<List<CommentsObject>>(json);
return comments;
}
else
{
throw new Exception("Errorhandling message");
}
}
It's not ideal (and not completely an answer but more of a work around) but I created models that mock the reddit response json to make deserialization super easy. I use JsonProperty attributes on my model properties to pretty up the models a bit.
Here are the models
And since my models directly mock the json I can just use json.net's generic deserialize method.

Categories