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

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!

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

Map JSON to C# Class when attribute names have spaces and reserved words

I am consuming a REST API service. In the service response JSON, there are attribute names that include spaces and reserved words. I'm trying to map it to a C# class, but I can't assign attribute names that are the same as the field names.
Currently, the mapping only succeeds when the JSON attribute and C# class name of a field matches exactly, otherwise the value comes in as null.
Below is the JSON returned from the service:
{
"value": [ {
"accountNo": "JKBXXXXXXXXXVNX1",
"mainSalesPerson": "XXXXX",
"accountName": "XXXXXX",
"ledgerBalance": "-2,298.70",
"T+3": "0.00",
"T+4": "0.00",
"T+5 and Above": "2,298.70",
"riskRatedPortfolioValue": "109,057.50",
"exposure": "106,758.80",
"costToFirm": "",
"incomeToFirm": "14.59",
"costToIncome(%)": "",
"exposure(%)": "2.11",
"O/S Balance": "-2,298.70"
}],
"success": true
}
I have used the following mapping class:
public class CountObject
{
public string value { get; set; }
public string success { get; set; }
}
public class RiskManagementQueryValueObject
{
public string accountNo { get; set; }
public string mainSalesPerson { get; set; }
public string accountName { get; set; }
public string ledgerBalance { get; set; }
[SerializeAs(Name = "T+3")]
public string T3 { get; set; }
[SerializeAs(Name = "T+4")]
public string T4 { get; set; }
[SerializeAs(Name = "T+5 and Above")]
public string T5_and_Above { get; set; }
public string riskRatedPortfolioValue { get; set; }
public string exposure { get; set; }
public string costToFirm { get; set; }
public string incomeToFirm { get; set; }
[SerializeAs(Name = "costToIncome(%)")]
public string costToIncome { get; set; }
[SerializeAs(Name = "exposure(%)")]
public string exposure_per { get; set; }
[SerializeAs(Name = "O/S Balance")]
public string OS_Balance { get; set; }
}
public class RiskManagementQueryHeadertObject
{
public List<RiskManagementQueryValueObject> value { get; set; }
public bool success { get; set; }
}
And this how I talk to the service:
public List<RiskManagementQueryValueObject> getOverdues()
{
List<RiskManagementQueryValueObject> overdues = new List<RiskManagementQueryValueObject>();
var count = 0.0;
try
{
var restProxy = new RESTProxy();
var request = restProxy.initRestRequest("/cam/riskmanagement/1/query/count", Method.POST, new { requestCriteriaMap = new { currency = "LKR" } });
CountObject data = restProxy.Execute<CountObject>(request);
if (data.success.ToString().ToLower() != "true")
return null;
//get the page count
var pageCount = Math.Truncate(count / 300) + 1;
for (int j = 0; j < pageCount; j++)
{
var request2 = restProxy.initRestRequest(string.Format("/cam/riskmanagement/1/query/{0}", (j + 1).ToString()), Method.POST, new { requestCriteriaMap = new { currency = "LKR" } });
RiskManagementQueryHeadertObject data2 = restProxy.Execute<RiskManagementQueryHeadertObject>(request2);
overdues.AddRange(data2.value);
}
}
catch (Exception)
{
overdues = null;
}
return overdues;
}
public class RESTProxy
{
string DEFAULT_HOST = "http://xxx.xxx.xxx.xxx:xxx/";
string DEFAULT_MODULE = "xxx-rest";
string DEFAULT_USER = "xxx:xxx:xxx";
string DEFAULT_PASS = "xxx";
public T Execute<T>(RestRequest request) where T : new()
{
var client = new RestClient(string.Concat(DEFAULT_HOST, DEFAULT_MODULE))
{
Authenticator = new DigestAuthenticator(DEFAULT_USER, DEFAULT_PASS, DEFAULT_HOST)
};
var response = client.Execute<T>(request);
if (response.ErrorException != null)
{
throw response.ErrorException;
}
return response.Data;
}
public RestRequest initRestRequest(string pRestResourceName, Method pRestServiceVerb, object pRestRequestBody)
{
var request = new RestRequest(pRestResourceName, pRestServiceVerb);
request.RequestFormat = DataFormat.Json;
if (pRestRequestBody != null)
{
request.AddBody(pRestRequestBody);
}
return request;
}
}
How can I resolve this and serialize all the fields into my class definition?
Using the JsonProperty attribute worked for me:
Example:
This C# class:
public class Product
{
[JsonProperty(PropertyName = "Name/ + 1")]
public string Name { get; set; }
}
maps to the following javascript object:
var input = {"Name/ + 1": "PostName"};
I solved the issue. I added [DeserializeAs(Name ="")] instead of [SerializeAs(Name ="")]. I just did this in my C# Map class:
public class RiskManagementQueryValueObject
{
public string accountNo { get; set; }
public string mainSalesPerson { get; set; }
public string accountName { get; set; }
public string ledgerBalance { get; set; }
[DeserializeAs(Name = "T+3")]
public string T3 { get; set; }
[DeserializeAs(Name = "T+4")]
public string T4 { get; set; }
[DeserializeAs(Name = "T+5 and Above")]
public string T5_and_Above { get; set; }
public string riskRatedPortfolioValue { get; set; }
public string exposure { get; set; }
public string costToFirm { get; set; }
public string incomeToFirm { get; set; }
[DeserializeAs(Name = "costToIncome(%)")]
public string costToIncome { get; set; }
[DeserializeAs(Name = "exposure(%)")]
public string exposure_per { get; set; }
[DeserializeAs(Name = "O/S Balance")]
public string OS_Balance { get; set; }
}

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

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...!

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);

Categories