Null when trying to load a JSON from Root PCL Xamarin - c#

Hi when trying to load a JSON file from the root of my PCL it breaks on this line Using (var reader = new StreamReader(stream)) and says its null.
here is the full method for loadJson()
public void LoadJson()
{
//Loads the JSON File in the Solution and Finds Correct ID of Accordion Hopefully!!
var assembly = typeof(App).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("MCETimeTest.TimeSheet.json");
string jsonString = "";
using (var reader = new StreamReader(stream))
{
jsonString = reader.ReadToEnd();
};
uoObj = JsonConvert.DeserializeObject<RootObject>(jsonString);
}
Edit: when stepping through the code stream is always null
and my classes for my json are:
//JSON Classes
public class RootObject
{
public List<LineItem> LineItems { get; set; }
}
public class Checks
{
public DateTime TheDate { get; set; }
public string JobNumber { get; set; }
public string CustomerName { get; set; }
public TimeSpan On1 { get; set; }
public TimeSpan Off1 { get; set; }
public TimeSpan On2 { get; set; }
public TimeSpan Off2 { get; set; }
public string Description { get; set; }
public string SingleHours { get; set; }
public string TimeHalfHours { get; set; }
public string DoubleHours { get; set; }
}
public class LineItem
{
public string Id { get; set; }
public string Customer { get; set; }
public List<Checks> Checks { get; set; }
}

Also looking over the solution it turns out that the JSON File in the root was not an Embedded Resource. After changing it, it works! sorry for the hassle!

Related

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.

JSON Deserialization to get some particular objects and Serialize with new Json format using C#

For my project I need to Deserialize a long JSON data from Wikipedia. Then I need to get some particular information like Title, Extract, Thumbnail Source, Co-ordinates from that JSON. After getting all these data I need to serialize it again in a new formatted JSON.Hence I wrote a code for this.But having lot of problem with this code. I gave a description of every error beside my coding.
I am using this api from wikipedia
https://en.wikipedia.org/w/api.php?format=json&action=query&redirects=1&generator=geosearch&prop=extracts|coordinates|pageimages&ggslimit=20&ggsradius=1000&ggscoord=52.5243700|13.4105300&&formatversion=2&exintro=1&explaintext=1&exlimit=20&coprop=type|dim|globe&colimit=20&piprop=thumbnail&pithumbsize=400&pilimit=20
My C# object for this json is as below-
public class Coordinate
{
public double lat { get; set; }
public double lon { get; set; }
public string primary { get; set; }
public string type { get; set; }
public string dim { get; set; }
public string globe { get; set; }
}
public class Thumbnail
{
public string source { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Page
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
public List<Coordinate> coordinates { get; set; }
public Thumbnail thumbnail { get; set; }
}
public class Query
{
public List<Page> pages { get; set; }
}
public class RootObject
{
public bool batchcomplete { get; set; }
public Query query { get; set; }
}
Now I create a C# Class to serialize my resulted Json object. I want my final Json in this way-
public class Poi
{
public string Title { set; get; }
public string Description { set; get; }
public List<PoiImage> Images { set; get; }
public string OpeningHours { set; get; }
public double AirDistanceInKm { set; get; }
public double Lon { set; get; }
public double Lat { set; get; }
}
public class PoiImage
{
public string ImageID { set; get; }
}
I am using this code to Deserialize and Seralize JSON objects. But having lot of problems which I have mentioned beside code.
Edited Code
using (WebClient client = new WebClient())
{
try
{
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&redirects=1&generator=geosearch&prop=extracts|coordinates|pageimages&ggslimit=20&ggsradius=1000&ggscoord=52.5243700|13.4105300&&formatversion=2&exintro=1&explaintext=1&exlimit=20&coprop=type|dim|globe&colimit=20&piprop=thumbnail&pithumbsize=400&pilimit=20");
var json = JsonConvert.DeserializeObject<RootObject>(response);
List<Poi> poi = new List<Poi>();
foreach (var page in json.query.pages)
{
Poi obj = new Poi();
obj.Title = page.title;
obj.Description =page.extract ;
var Image = new PoiImage();
var ImgfirstKey = page.thumbnail.source;
Image.ImageID = string.Format("{0:X}.jpg", ImgfirstKey.GetHashCode());
obj.Images = new List<PoiImage> {Image};
obj.Lat = page.coordinates.First().lat;
obj.Lon = page.coordinates.First().lon;
poi.Add(obj);
}
JsonSerializerSettings serializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented };
string result= Newtonsoft.Json.JsonConvert.SerializeObject(poi, serializerSettings);
Console.WriteLine(result);
}
catch(Exception)
{
}
}
Just move the serialize code outside of the foreach
and serialize the list<poi>
foreach (page in rootObject.Query.Pages){
//do the magic
//then
poi.add(obj)
}
JsonSerializerSettings serializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented };
Newtonsoft.Json.JsonConvert.SerializeObject(poi, serializerSettings);

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;

Extract data from Json string

I got a string containing Json. It looks like this:
"status_code":200,
"status_txt":"OK",
"data":
{
"img_name":"D9Y3z.png",
"img_url":"http:\/\/s1.uploads.im\/D9Y3z.png",
"img_view":"http:\/\/uploads.im\/D9Y3z.png",
"img_width":"167",
"img_height":"288",
"img_attr":"width=\"167\" height=\"288\"",
"img_size":"36.1 KB",
"img_bytes":36981,
"thumb_url":"http:\/\/s1.uploads.im\/t\/D9Y3z.png",
"thumb_width":360,
"thumb_height":360,
"source":"http:\/\/www.google.com\/images\/srpr\/nav_logo66.png",
"resized":"0",
"delete_key":"df149b075ab68c38"
}
I am trying to get a hold of the "img_url". I have Json.NET installed and I´ve found similar questions here..
for example something like this:
JObject o = JObject.Parse("{'People':[{'Name':'Jeff'},{'Name':'Joe'}]}");
// get name token of first person and convert to a string
string name = (string)o.SelectToken("People[0].Name");
In my case I changed ("People[0].Name") to ("img_url"),("img_url[0]) etc..no luck
This is my code now:
public string tempJson { get; set; }
public ActionResult SaveUploadedFile(string test)
{
using (WebResponse wrs = wrq.GetResponse())
using (Stream stream = wrs.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
tempJson = json;
}
}
Do I have to do something with the string before I can extract the value?
Thanks!
img_url is not a property of root object - it's a property of data object:
var obj = JObject.Parse(json);
var url = (string)obj["data"]["img_url"]; // http://s1.uploads.im/D9Y3z.png
Another option:
var url = (string)obj.SelectToken("data.img_url");
With help of this site
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(obj.data.img_url);
public class Data
{
public string img_name { get; set; }
public string img_url { get; set; }
public string img_view { get; set; }
public string img_width { get; set; }
public string img_height { get; set; }
public string img_attr { get; set; }
public string img_size { get; set; }
public int img_bytes { get; set; }
public string thumb_url { get; set; }
public int thumb_width { get; set; }
public int thumb_height { get; set; }
public string source { get; set; }
public string resized { get; set; }
public string delete_key { get; set; }
}
public class RootObject
{
public int status_code { get; set; }
public string status_txt { get; set; }
public Data data { get; set; }
}
You can also do the same thing with the use of dynamic keyword (without declaring above classes)
dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.data.img_url);

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