Json DeserializeObject exception: "reference not set to instance of an object" - c#

I'm having trouble deserializing a json string into objects. I have a similar instance working fine for a different class, but i can't seem to get this one to work correctly. Here is the class:
class Task
{
public string ProviderID { get; set; }
public string Id { get; set; }
public string UserEmail { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public string CompleteBy { get; set; }
public string CompleteAtLat { get; set; }
public string CompleteAtLon { get; set; }
public string PerformWithin { get; set; }
public string AdditionalInfo { get; set; }
public string UserCanReject { get; set; }
public string StartTime { get; set; }
public string CompleteTime { get; set; }
public string ActualCompleteLat { get; set; }
public string ActualCompleteLon { get; set; }
public string UserNotes { get; set; }
public static IList<Task> Get()
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url");
req.Method = "GET";
req.ContentType = "application/json";
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
string text = sr.ReadToEnd();
JObject jsonresponse = JObject.Parse(text);
Console.WriteLine(jsonresponse.ToString());
IList<JToken> results = jsonresponse["Stasks"].Children().ToList();
IList<Task> tasks = new List<Task>();
foreach (JToken result in results)
{
Task task = JsonConvert.DeserializeObject<Task>(result.ToString());
tasks.Add(task);
}
return tasks;
}
}
And here is a sample of the Json string i'm trying to deserialize.
{
"STasks":[
{
"ProviderId":"xxxxx",
"Id":"xxxxx",
"UserEmail":"xxxxx",
"Name":"test",
"Status":"Completed",
"CompleteBy":"2014-11-15T15:17:00.0000000Z",
"CompleteAtLat":0,
"CompleteAtLon":0,
"PerformWithin":50,
"AdditionalInfo":"trsgghghfhghh",
"UserCanReject":true,
"STaskActivities":[
{
"Instruction":"fsdgggdg",
"OutcomeId":"00000000000000000000000000000000",
"CompleteTime":"2014-11-14T15:19:37.0000000Z",
"ActivityType":"Instruction"
}
],
"STaskHistories":[
{
"EventDate":"2014-11-14T15:18:27.2975697Z",
"Status":"Draft"
},
{
"EventDate":"2014-11-14T15:18:54.8263294Z",
"Status":"Sent"
},
{
"EventDate":"2014-11-14T15:19:37.7176027Z",
"Status":"Accepted"
},
{
"EventDate":"2014-11-14T15:19:49.0975573Z",
"Status":"Completed"
}
],
"StartTime":"2014-11-14T15:19:37.0000000Z",
"CompleteTime":"2014-11-14T15:19:47.0000000Z",
"ActualCompleteLat":52.6091012845814,
"ActualCompleteLon":4.75544677437253,
"UserNotes":"Fyujvhfdkskbvdskbdvsbkdsvhkj"
}
]
}
I couldn't find any sort of detailed explanation of how this method works exactly, so maybe i'm missing something here. If i don't have a property in my class but it does appear in the Json, then it should be ignored, right?

I think that you're just parsing up the wrong JSON tree (pun!).
When I map out your JSON into classes, the deserialization works as expected. Try this:
Top-level JSON mapping:
public class STasksContainer
{
public STask[] STasks{get;set;}
}
Also add this mapping for the primary array element:
public class STask
{
public string ProviderId {get;set;}
public string Id{get;set;}
public string UserEmail{get;set;}
public string Name{get;set;}
public string Status{get;set;}
public string CompleteBy{get;set;}
public double CompleteAtLat{get;set;}
public double CompleteAtLon{get;set;}
public int PerformWithin{get;set;}
public string AdditionalInfo{get;set;}
public bool UserCanReject{get;set;}
public string StartTime{get;set;}
public string CompleteTime{get;set;}
public double ActualCompleteAtLat{get;set;}
public double ActualCompleteAtLon{get;set;}
public string UserNotes{get;set;}
public STaskActivity[] STaskActivities{get;set;}
public STaskHistory[] STaskHistories{get;set;}
}
And lastly, add in the mappings for the two nested array elements within STask:
public class STaskActivity
{
public string Instruction{get;set;}
public string OutcomeId{get;set;}
public string CompleteTime{get;set;}
public string ActivityType{get;set;}
}
public class STaskHistory
{
public string EventDate{get;set;}
public string Status{get;set;}
}
You can test the code:
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
string text = sr.ReadToEnd();
var sTaskRoot = JsonConvert.DeserializeObject<STasksContainer>(text);
}
HTH...!

Related

How to deserialize an object and pass it to a response model

i have a json string that i deserialize as follows.
using (var streamReader = new StreamReader(httpResponsePayment.GetResponseStream()))
{
var data = streamReader.ReadToEnd();
result = JsonConvert.DeserializeObject<TestResponse>(data);
}
the data object looks as follows
"{\"responseCode\":2402,\"responseMessage\":\"hello\",\"amount\":0,\"acquirer\":{\"account\":{\"Number\":\"4587-54884-784848\"},\"Tag\":\"TF1234569775548494\"}}"
i pass this object to my TestResponse class
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
}
i can pass the above 3 objects correctly. I dont know how to pass the acquirer object to the TestResponse
acquirer = new
{
account= new
{
Number="4587-54884-784848"
},
Tag= "TF1234569775548494"
}
i tried doing something like this
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
List<Acquirers> acquirer =new List<Acquirers>();
}
public class Acquirers
{
public string Tag { get; set; }
}
also tried
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
public string Number {get;set;} //returns null
public string Tag {get;set;} // returns null
}
can someone please guide me
class Program
{
static void Main(string[] args)
{
var json = "{\"responseCode\":2402,\"responseMessage\":\"hello\",\"amount\":0,\"acquirer\":{\"account\":{\"Number\":\"4587-54884-784848\"},\"Tag\":\"TF1234569775548494\"}}";
var result = JsonConvert.DeserializeObject<Root>(json);
}
}
public class Account
{
public string Number { get; set; }
}
public class Acquirer
{
public Account account { get; set; }
public string Tag { get; set; }
}
public class Root
{
public int responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
public Acquirer acquirer { get; set; }
}
you can using this link = https://json2csharp.com/
for convert model

C# Deserialize a Json string with one array and one bool value

I am trying to deserialize a json string, but only the bool value is appending to my class, where as the array values are always null .
public static EmployeeInformation GetEngineerAdditionInfo(ProjectUserRoles role)
{
EmployeeInformation engineerAdditionalInfo = new EmployeeInformation();
var apiBaseUri = string.Empty;
apiBaseUri = "https:example.com";
Uri newUri = new Uri(apiBaseUri);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(newUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
using (var response = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string line = reader.ReadToEnd();
engineerAdditionalInfo = JsonConvert.DeserializeObject<EmployeeInformation>(line);
}
}
}
And my classes are
public class EmployeeInformation
{
public bool IsSuccess { get; set; }
List<EmployeeBasicDetails> EmployeeBasicDetails { get; set; }
}
public class EmployeeBasicDetails
{
public int UserId { get; set; }
public string EmployeeId { get; set; }
public string EmailId { get; set; }
public string EmployeeName { get; set; }
}
My Json string will be as follows,
{"IsSuccess":true,"EmployeeBasicDetails":[{"UserId":124,"EmployeeId":"SS124","EmailId":"example#example.com","EmployeeName":"Example"},{"UserId":125,"EmployeeId":"SS125","EmailId":"example#example.com","EmployeeName":"Example"},{"UserId":126,"EmployeeId":"SS126","EmailId":"example#example.com","EmployeeName":"Example"},{"UserId":127,"EmployeeId":"SS127","EmailId":"example#example.com","EmployeeName":"Example"}]}
Did i missed anything? Or is there any other way to get the array list from json string ?
Thanks in advance,
Dinesh.
This is just a guess, but I think you forgot to set your EmployeeBasicDetails to public:
public class EmployeeInformation
{
public bool IsSuccess { get; set; }
public List<EmployeeBasicDetails> EmployeeBasicDetails { get; set; }
}
public class EmployeeBasicDetails
{
public int UserId { get; set; }
public string EmployeeId { get; set; }
public string EmailId { get; set; }
public string EmployeeName { get; set; }
}
Hope it helps!

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