converting from json to c# class object - c#

I try to convert from json to c# class object, cause my final step will be put this all data into local db. I have no problem with taking this data like one big string, so the Url is good typed, but it's not my goal.
this is the json data, here we have two objects
[{"id":"1","category":"1","name":"good 1","prize":"12.3","prize2":"13.4","elements":"row,column,paper","secid":"2131","description":"nice","quality":"best","dateofcoming":"2013-12-20 18:08:50","date":"2013-12-20 00:00:00"},
{"id":"2","category":"2","name":"good","prize":"14.3","prize2":"15.4","elements":"up,down,left","secid":"2132","description":"nc","quality":"best","dateofcoming":"2013-12-20 18:10:55","date":"2013-12-20 00:00:00"}]
I try by this way which I found in the book:
private void getBookData()
{
// we creating the request details to the site which give us
// back the json data
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("here is my adress");
request.Accept = "and header";
// starting the request
request.BeginGetResponse(callback_with_food_info, request);
}
private void callback_with_food_info(IAsyncResult ar)
{
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
// we get the response
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(ListOfObjects));
Stream responseStream = response.GetResponseStream();
ListOfObjects listOfobj = (ListOfObjects)deserializer.ReadObject(responseStream);
String fsdfsdf = "how how how";
}
and in the row when we ReadObject
ListOfObjects listOfobj = (ListOfObjects)deserializer.ReadObject(responseStream);
I get exception "System.InvalidCastException", my List class look like this and it was created by http://json2csharp.com/
public class DetailsOfObject
{
public string id { get; set; }
public string category { get; set; }
public string name { get; set; }
public string prize { get; set; }
public string prize2 { get; set; }
public string elements { get; set; }
public string secid { get; set; }
public string description { get; set; }
public string quality { get; set; }
public string dateofcoming { get; set; }
public string date { get; set; }
}
public class ListOfObjects
{
public DetailsOfObject list {get; set;}
}
Any advice how to finally convert this json data

You need to add Data attributes to model
[DataContract]
public class DetailsOfObject
{
[DataMember]
public string id { get; set; }
and change deserialize line
List<DetailsOfObject> listOfobj = (List<DetailsOfObject>)deserializer.ReadObject(responseStream);

Related

Binding JSON values in my server side is getting failed

I want to use the json values in my c# code. So I have written the code like below
public static void WriteToIEMService(string jsonValue)
{
string TimeFormatText = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");
string strFileCreationDate = DateTime.Now.ToString("dd/MM/yyyy");
string strFileName = ConfigurationManager.AppSettings["IEM_SERVICEFILE"].ToString();
try
{
using (StreamWriter sw = File.CreateText(ConfigurationManager.AppSettings["LogFileDirectory"].ToString() + strFileName + "_" + strFileCreationDate + ".txt"))
{
List<MasterServiceResponse> records = JsonConvert.DeserializeObject<List<MasterServiceResponse>>(jsonValue);
sw.WriteLine("IEM Service started and send data to IEM below");
foreach (MasterServiceResponse record in records)
{
sw.WriteLine(record.SapId);
}
}
}
catch (Exception)
{
throw;
}
}
But I am getting error as
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[IPColoBilling_BKP.App_Code.MasterServiceResponse]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Please help
EDIT
My json values is as below
{"SiteData":[{"SAPId":"I-UW-SRPR-ENB-I001","SiteRFEIDate":"03-11-2014","SiteRFSDate":"03-11-2014","ID_OD":"ID","ID_ODchangeDate":"04-11-2018","NoofRRHBase":"0","RRHBaseChangeEffectiveDate":"","No_Of_Tenancy":"3","TenancyChangeEffectiveDate":"03-11-2014","SiteStatus":"Active","SiteDropDate":""}]}
UPDATE
public class MasterServiceResponse
{
public string SapId { get; set; }
public string AcknowledgementID { get; set; }
public string FlagResponse { get; set; }
public string ResponseMessage { get; set; }
public string GisStatus { get; set; }
public string GisSendDate { get; set; }
public string SiteRFEIDate { get; set; }
public string SiteRFSDate { get; set; }
public string SiteRRHDate { get; set; }
public string NoofRRHBase { get; set; }
}
Update: A stated by Panagiotis Kanavos, You are not creating Root object, so you have to restructure your models.
Don't know what your Model looks like, But this error message says your giving json object where it is expecting JSON array,
Below is the model you should be using
public class SiteData
{
public string SAPId { get; set; }
public string SiteRFEIDate { get; set; }
public string SiteRFSDate { get; set; }
public string ID_OD { get; set; }
public string ID_ODchangeDate { get; set; }
public string NoofRRHBase { get; set; }
public string RRHBaseChangeEffectiveDate { get; set; }
public string No_Of_Tenancy { get; set; }
public string TenancyChangeEffectiveDate { get; set; }
public string SiteStatus { get; set; }
public string SiteDropDate { get; set; }
}
public class RootObject
{
public List<SiteData> SiteData { get; set; }
}
You also have to change the deserializing code
E.g.
RootObject records = JsonConvert.DeserializeObject<RootObject>(jsonValue);
foreach (SiteData record in records.SiteData)
{
sw.WriteLine(record.SapId);
}
As the error mentions, you cannot deserialize JSON object to list. So instead of:
List<MasterServiceResponse> records = JsonConvert.DeserializeObject<List<MasterServiceResponse>>(jsonValue);
You should update have something like:
MyObject obj = JsonConvert.DeserializeObject<MyObject>(jsonValue);
The exception message tells you that the JSON string contains single object, but you're tried to deserialize it into List<MasterServiceResponse> collection.
You should create a class to hold List<MasterServiceResponse>:
public class SiteData
{
public List<MasterServiceResponse> MasterServiceResponse { get; set; }
}
Then you should replace this line:
List<MasterServiceResponse> records = JsonConvert.DeserializeObject<List<MasterServiceResponse>>(jsonValue);
to return single object like this:
SiteData records = JsonConvert.DeserializeObject<SiteData>(jsonValue);
Reference:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1
Because your JSON start with a key "SiteData" which has an array value, you need to create a helper class to match that structure (e.g. class SiteResponse) with a property named SiteData of type List<MasterServiceResponse>.
Code:
public class SiteResponse
{
public List<MasterServiceResponse> SiteData { get; set; }
}
private static void TestJson()
{
var jsonValue = "{\"SiteData\":[{\"SAPId\":\"I-UW-SRPR-ENB-I001\",\"SiteRFEIDate\":\"03-11-2014\",\"SiteRFSDate\":\"03-11-2014\",\"ID_OD\":\"ID\",\"ID_ODchangeDate\":\"04-11-2018\",\"NoofRRHBase\":\"0\",\"RRHBaseChangeEffectiveDate\":\"\",\"No_Of_Tenancy\":\"3\",\"TenancyChangeEffectiveDate\":\"03-11-2014\",\"SiteStatus\":\"Active\",\"SiteDropDate\":\"\"}]}";
var siteResponse = JsonConvert.DeserializeObject<SiteResponse>(jsonValue);
List<MasterServiceResponse> records = siteResponse.SiteData;
}
Working demo here:
https://dotnetfiddle.net/wzg8AK

Deserialize Object into a class does not work

I am trying to set a class for a token using DeserializeObject from the json object i get back from my api. However when i run the below code it sets all the values to null or 0, not the result i am getting from the api.
cs code
var resultString = await result.Content.ReadAsStringAsync();
var post = JsonConvert.DeserializeObject<Token>(resultString);
class
public class Token : ContentPage
{
public int StaffID { get; set; }
public string TokenApi { get; set; }
public string StaffForename { get; set; }
public string StaffSurname { get; set; }
public string StaffEmail { get; set; }
public int PrimaryStaffRoleID { get; set; }
}
JSON response
"{\"code\":201,\"status\":\"Success\",\"message\":\"Object found\",\"data\":{\"StaffID\":14,\"StaffSurname\":\"Test\",\"StaffForename\":\"Test\",\"StaffEmail\":\"test#test.com\",\"PrimaryStaffRoleID\":5,\"TokenApi\":\"testToken\"}}"
Firstly the data which you are trying to map is inside another property in your json called Data and secondly your json does not have a property with name Token
The problem actually is you are not using the correct type that reflects your json, means you don't have correct c# type which would get mapped to json, you can generate correct types using json2charp.com , the correct classes for it are :
public class Data
{
public int StaffID { get; set; }
public string StaffSurname { get; set; }
public string StaffForename { get; set; }
public string StaffEmail { get; set; }
public int PrimaryStaffRoleID { get; set; }
public string TokenApi { get; set; }
}
public class RootObject
{
public int code { get; set; }
public string status { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
Now deserializing using RootObject as type parameter would work perfectly fine like:
var resultString = await result.Content.ReadAsStringAsync();
var post = JsonConvert.DeserializeObject<RootObject>(resultString);
A more good option is to use QuickType.IO which would even generate code for you in c# or any other language that they are supporting.
If you analyze the JSON that you posted, the object that you're trying to Deserialize is inside the "data" property of your json.
I suggest you creating a class to represent the JsonResponse with a Data property. This will be your Token
You are retrieved a string that match this object
public string code {get;set;}
public string Success {get;set;} ...
And Token is matching data in json, so
var post = JsonConvert.DeserializeObject<Token>(resultString.data);
would be better.

How to bind multilevel json data to a repeater in asp.net or converting json data to data table

I want to bind the Json data to the repeater I know only one process that is converting the Json data to data table and then binding data but here I am receiving multilevel json data i do't know how to convert them to data table
input json data:
{"apiAvailableBuses":
[{"droppingPoints":null,"availableSeats":40,"partialCancellationAllowed":false,"arrivalTime":"01:00 AM","cancellationPolicy":"[{\"cutoffTime\":\"1\",\"refundInPercentage\":\"10\"},{\"cutoffTime\":\"2\",\"refundInPercentage\":\"50\"},{\"cutoffTime\":\"4\",\"refundInPercentage\":\"90\"}]","boardingPoints":[{"time":"07:40PM","location":"K.P.H.B,Beside R.S Brothers","id":"2238"}],"operatorName":"Apple I Bus","departureTime":"8:00 PM","mTicketAllowed":false,"idProofRequired":false,"serviceId":"6686","fare":"1000","busType":"Hi-Tech A/c","routeScheduleId":"6686","commPCT":9.0,"operatorId":203,"inventoryType":0},
{
"droppingPoints":null,"availableSeats":41,"partialCancellationAllowed":false,"arrivalTime":"06:00 AM","cancellationPolicy":"[{\"cutoffTime\":\"1\",\"refundInPercentage\":\"10\"},{\"cutoffTime\":\"2\",\"refundInPercentage\":\"50\"},{\"cutoffTime\":\"4\",\"refundInPercentage\":\"90\"}]","boardingPoints":[{"time":"08:00PM","location":"Punjagutta,","id":"2241"}],"operatorName":"Royalcoach Travels","departureTime":"8:00 PM","mTicketAllowed":false,"idProofRequired":false,"serviceId":"6736","fare":"800","busType":"VOLVO","routeScheduleId":"6736","commPCT":9.0,"operatorId":243,"inventoryType":0}
I am trying to convert it to data table by
public void getavailablebuses()
{
string url = string.Format(HttpContext.Current.Server.MapPath("files/getavailablebuses.json"));
using (WebClient client = new WebClient())
{
string json = client.DownloadString(url);
var result = JsonConvert.DeserializeObject<RootObject>(json);
string mm = JObject.Parse(json).SelectToken("apiAvailableBuses").ToString();
// var boardingpoint = JObject.Parse(mm).SelectToken("boardingPoints").ToString();
var Availablebuses = JObject.Parse(json).SelectToken("apiAvailableBuses").ToString();
DataTable dt = (DataTable)JsonConvert.DeserializeObject(Availablebuses, (typeof(DataTable)));
}
public class apiresult
{
public string message { get; set; }
public string success { get; set; }
}
public class RootObject
{
public apiresult apiStatus;
public List<apiAvailableBuses> apiAvailableBuses{ get; set; }
// public string apiAvailableBuses { get; set; }
}
public class apiAvailableBuses
{
public string serviceId { get; set; }
public string fare { get; set; }
public string busType { get; set; }
public string departureTime { get; set; }
public string operatorName { get; set; }
public string cancellationPolicy { get; set; }
public List<boardingpoints> boardingpoints { get; set; }
public string droppingPoints { get; set; }
public string inventoryType { get; set; }
public string routeScheduleId { get; set; }
public int availableSeats { get; set; }
public string arrivalTime { get; set; }
public Boolean idProofRequired { get; set; }
public Boolean partialCancellationAllowed { get; set; }
public int operatorId { get; set; }
public double commPCT { get; set; }
public string mTicketAllowed { get; set; }
}
public class boardingpoints
{
public string location { get; set; }
public string id { get; set; }
public string time { get; set; }
}
public class cancellationPolicy
{
public string cutoffTime { get; set; }
public string refundInPercentage { get; set; }
}
Here in the data table I am unable to get the boarding points, dropping points and cancellation policy
if I load cancellation policy as list or JObject I am getting error
so here I am loading cancellation policy as string.
but I am unable to load boarding points and dropping points.
Please help with this I am scratching my head from two days. Thanks in advance
"I know only one method to bind data to a repeater i.e data table." So this is a perfect opportunity to learn other ways, wouldn't you say?
Why don't you work with the result of JsonConvert.DeserializeObject<RootObject>(json);? This is a RootObject that has a property called apiAvailableBuses which seems to be exactly what you need to bind to your repeater, no?
By the way, a bit of code review:
apiresult and apiAvailableBuses violate Microsoft's rules WRT class names: those should be in PascalCase. Same for the properties of apiresult, e.g. message and success. Same for the properties of apiAvailableBuses.
RootObject has a public field: apiStatus. That probably needs to be a a property with a getter/setter.
Moreover, apiAvailableBuses is plural, which is incorrect, since the data therein is of only one bus. Same for boardingpoints: the class contains data for a single point, not multiple.
Be consistent: if you use string, then also use bool and not Boolean.

JavaScriptSerializer, Parsing Json from HttpRequest, put pars into a table to be displayed

I made a call to a web server called Sample ApI. I want to be able to parse that data that's in json or xml, either would be nice and display it in a table format. This is what I have so far.
All I want is to be able to parse the data that's in this string _responseAsString and display a table. I don't know how to start it, I just know JavaScriptSerialzer parseXXX = new Java...lizer(). Please help me or assist in the right direction.
public class Event
{
public string event_key { get; set; }
public string user_token { get; set; }
public string event_set_key { get; set; }
public string event_type { get; set; }
public string event_date { get; set; }
public string event_amount { get; set; }
public string event_location_key { get; set; }
public string event_location_name { get; set; }
public string event_location_city { get; set; }
public string event_location_state { get; set; }
public string event_location_country { get; set; }
public string event_acknowledged { get; set; }
}
public ActionResult GetEvent()
{
try
{
string at = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
string et = "KI2XfwQNByLPFdK4i3a74slLT7sjjzYRi9RR7zEtCoQ%3D";
string t = "20111128183020";
string _checkingUrl = String.Format("http://172.22.22.10/SampleAPI/Event/GetEvents?at={0}&et={1}&t={2}&responseFormat=json", at, et, t);
System.Net.HttpWebRequest request=System.Net.WebRequest.Create(_checkingUrl) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response=request.GetResponse() as System.Net.HttpWebResponse;
System.IO.StreamReader _readResponse=new System.IO.StreamReader(response.GetResponseStream());
//The encrypted dynamics response in either xml or json
string _responseAsString=_readResponse.ReadToEnd();
JavaScriptSerializer parseResponse = new JavaScriptSerializer();
List<Event> events = parseResponse.Deserialize<List<Event>>(_responseAsString);
// this below is to make sure i was receiving my json data.
return Content(_responseAsString);
_readResponse.Close();
}
catch (Exception e)
{
//log error
}
return View();
}
This is the json data I receive when I make the http request:
"[{\"event_key\":\"cc2a1802-2b04-4530-ad50-0d4f0ed19dd3\",\"user_token\":\"40e62a11-40c4-408d-8cdd-1293cbaf9a41\",\"event_set_key\":\"615017f2-ae28-4b8d-9def-cf043642b928\",\"event_type\":\"Arrival\",\"event_date\":\"6/20/2011
4:15:28
PM\",\"event_amount\":\"100\",\"event_location_key\":\"50fc1c22-d77b-4a91-b31d-da036827060b\",\"event_location_name\":\"Store2\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"True\"},{\"event_key\":\"2ac9e25e-137c-4a72-8cc5-157d67ea66c1\",\"user_token\":\"58cb4fcd-e140-4232-88c9-06eecb95b63d\",\"event_set_key\":\"00710ca7-f5d7-4c7a-bbfb-95491ae278ef\",\"event_type\":\"Arrival\",\"event_date\":\"9/23/2011
4:15:28
PM\",\"event_amount\":\"45\",\"event_location_key\":\"5a732dd5-9459-4cdd-a980-f3daf1a07343\",\"event_location_name\":\"Store4\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"False\"},{\"event_key\":\"386b1fa1-11b2-48d9-b7f1-4bbe21ced487\",\"user_token\":\"c3d8b7ff-d85f-42a8-98f6-e091b48c2280\",\"event_set_key\":\"dc55843b-f8cf-4e8a-9091-188ce0609fe1\",\"event_type\":\"Arrival\",\"event_date\":\"9/18/2011
4:15:28
PM\",\"event_amount\":\"100\",\"event_location_key\":\"be6d4fb4-c0e3-4303-b70d-7a22b721aa56\",\"event_location_name\":\"Store1\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"False\"}]"
The JSON website has some good information on this.
For older browsers, you would eval the string (with some brackets to make it work):
var myObject = eval('(' + myJsonText + ')');
And these days, we tend to use
JSON.parse(myJsonText);
And server side, in C#
var serializer = new JavaScriptSerializer();
T obj = serializer.Deserialize<T>(myJsonText);
First of all...
If you're just passing through the JSON message returned from some other API, why not just return their response string verbatim (in other words, why deserialize it at all)?
public ActionResult GetEvent()
{
string at = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
string et = "KI2XfwQNByLPFdK4i3a74slLT7sjjzYRi9RR7zEtCoQ%3D";
string t = "20111128183020";
string _checkingUrl = String.Format("http://172.22.22.10/SampleAPI/Event/GetEvents?at={0}&et={1}&t={2}&responseFormat=json", at, et, t);
System.Net.HttpWebRequest request=System.Net.WebRequest.Create(_checkingUrl) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response=request.GetResponse() as System.Net.HttpWebResponse;
using (var readResponse= new StreamReader(response.GetResponseStream()))
{
return Content(readResponse.ReadToEnd(), "application/json");
}
}
Then read on
It's possible to use a JSON text reader to break apart the JSON message into a table of name/value pairs, but I think that's missing the point in your case. If the message is constant, just create a class that represents each element in the JSON message and parse it. I used json2csharp to stub such a class:
public class Event
{
public string event_key { get; set; }
public string user_token { get; set; }
public string event_set_key { get; set; }
public string event_type { get; set; }
public string event_date { get; set; }
public string event_amount { get; set; }
public string event_location_key { get; set; }
public string event_location_name { get; set; }
public string event_location_city { get; set; }
public string event_location_state { get; set; }
public string event_location_country { get; set; }
public string event_location_lat { get; set; }
public string event_location_long { get; set; }
public string event_description { get; set; }
public string event_acknowledged { get; set; }
}
Then use your favorite JSON serializer to deserialize into a list of these objects:
var serializer = new JavaScriptSerializer();
var events = serializer.Deserialize<List<Event>>(responseAsString);
(I prefer JSON.NET, here's the equivalent to the block above)
var events = JsonConvert.DeserializeObject<List<Event>>(responseAsString);
If you actually do need to be able to read a stream of text and generically create a table of name/value pairs, I'd use JSON.NET's LINQ-to-JSON or the JsonTextReader.

How to read Google AJAX Feed API results from C# code?

I want to use Goolge AJAX Feed API in my C# console application to save return feeds as C# collection so i can use this .net collcetion in my .net application.
I noticed google give a Java Access Code Snippets but I have no idea how to coding it in C#.
I know there is a very good .net opensource library Json.NET we can use to read and write JSON formatted data.
Can someone give me an exmpale how to use C# and Json.NET play with Google AJAX Feed API?
Final Solution:
public class FeedApiResult
{
public ResponseData responseData { get; set; }
public string responseDetails { get; set; }
public string responseStatus { get; set; }
}
public class ResponseData
{
public Feed feed { get; set; }
}
public class Feed
{
public string title { get; set; }
public string link { get; set; }
public string author { get; set; }
public string description { get; set; }
public string type { get; set; }
public List<Entry> entries { get; set; }
}
public class Entry
{
public string title { get; set; }
public string link { get; set; }
public string author { get; set; }
public string publishedDate { get; set; }
public string contentSnippet { get; set; }
public string content { get; set; }
}
var url = "http://ajax.googleapis.com/ajax/services/feed/load?q=http%3A%2F%2Fwww.digg.com%2Frss%2Findex.xml&v=1.0";
var wc = new WebClient();
var rawFeedData = wc.DownloadString(url);
//You can use System.Web.Script.Serialization if you don't want to use Json.NET
JavaScriptSerializer ser = new JavaScriptSerializer();
FeedApiResult foo = ser.Deserialize<FeedApiResult>(rawFeedData);
//Json.NET also return you the same strong typed object
var apiResult = JsonConvert.DeserializeObject<FeedApiResult>(rawFeedData);
I've just looked at the examples, and here is how I'd go about it.
Construct the feed Url (read the documentation)
Use the WebClient to Download the URL as a String.
Use Json.NET to reads the string.
Use a for-loop to read each entries
For example, a quick untested hack:
// 1.
var url = "'http://ajax.googleapis.com/ajax/services/feed/load?q=http%3A%2F%2Fwww.digg.com%2Frss%2Findex.xml&v=1.0";
// 2.
var wc = new WebClient();
var rawFeedData = wc.DownloadString(url);
// 3.
var feedContent = JObject.Parse(rawFeedData);
// ...
var entries = feedContent["entries"];
for (int i = 0; i < entries.Length; i++) {
var entry = entries[i];
// insert entry into your desired collection
}
If however, you want strongly-typed class, you must first make a class that "looks like" the data that is returned from the feed api first, i.e.
public class FeedApiResult {
public FeedApiFeedObj responseData { get; set; }
// snip ...
}
public class FeedApiFeedObj {
public string title { get; set; }
public string link { get; set; }
// snip ...
}
Then in step #3, you can use the deserializing method like this:
var apiResult = JsonConvert.DeserializeObject<FeedApiResult>(feedContent)
...
Hope this helps!

Categories

Resources