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);
Related
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.
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!
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;
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");
}
I am trying to parse Open Exchange Rates JSON in Json, and I'm using this approach:
HttpWebRequest webRequest = GetWebRequest("http://openexchangerates.org/latest.json");
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
}
var serializer = new JavaScriptSerializer();
CurrencyRateResponse rateResponse = serializer.Deserialize<CurrencyRateResponse>(jsonResponse);
If I understand the JavaScriptSerializer.Deserialize properly I need to define and object to turn the Json into.
I can successfully serialize it using datatypes like this:
public class CurrencyRateResponse
{
public string disclaimer { get; set; }
public string license { get; set; }
public string timestamp { get; set; }
public string basePrice { get; set; }
public CurrencyRates rates { get; set; }
}
public class CurrencyRates
{
public string AED { get; set; }
public string AFN { get; set; }
public string ALL { get; set; }
public string AMD { get; set; }
}
I would like to be able to replay "CurrencyRates rates" with something like:
public Dictionary<string, decimal> rateDictionary { get; set; }
but the parser always returns the rateDictionary as null. Any idea if this is possible, or do you have a better solution?
Edit:
Json looks like this:
{
"disclaimer": "this is the disclaimer",
"license": "Data collected from various providers with public-facing APIs",
"timestamp": 1328880864,
"base": "USD",
"rates": {
"AED": 3.6731,
"AFN": 49.200001,
"ALL": 105.589996,
"AMD": 388.690002,
"ANG": 1.79
}
}
If your json is like:
{"key":1,"key2":2,...}
then you should be able to do:
Dictionary<string, string> rateDict = serializer.Deserialize<Dictionary<string, string>>(json);
This compiles:
string json = "{\"key\":1,\"key2\":2}";
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var dict = ser.Deserialize<Dictionary<string, int>>(json);
You should be able to figure it out yourself from here.
This code works with your sample data
public class CurrencyRateResponse
{
public string disclaimer { get; set; }
public string license { get; set; }
public string timestamp { get; set; }
public string #base { get; set; }
public Dictionary<string,decimal> rates { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();
var obj = ser.Deserialize<CurrencyRateResponse>(json);
var rate = obj.rates["AMD"];
Below code will work fine, CurrencyRates is collection so that by using List we can take all reates.
This should work!!
public class CurrencyRateResponse
{
public string disclaimer { get; set; }
public string license { get; set; }
public string timestamp { get; set; }
public string basePrice { get; set; }
public List<CurrencyRates> rates { get; set; }
}
public class CurrencyRates
{
public string AED { get; set; }
public string AFN { get; set; }
public string ALL { get; set; }
public string AMD { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();
var obj = ser.Deserialize<CurrencyRateResponse>(json);
var rate = obj.rates["AMD"];