Deserializing JSON List object - c#
I receive this JSON object from a web request:
"\"[{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-12T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-17T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-13T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-18T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-14T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-19T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-15T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-20T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"},{\\\"EventId\\\":25,\\\"StartDate\\\":\\\"2014-06-16T12:00:00\\\",\\\"EndDate\\\":\\\"2014-06-21T12:00:00\\\",\\\"Title\\\":\\\"Test\\\",\\\"Description\\\":\\\"desc\\\",\\\"Teaser\\\":\\\"teaser\\\",\\\"PhoneNumber\\\":null,\\\"Email\\\":null,\\\"AddressOne\\\":null,\\\"AddressTwo\\\":null,\\\"City\\\":null,\\\"State\\\":null,\\\"ZipCode\\\":null,\\\"Country\\\":null,\\\"RegistrationUrl\\\":null,\\\"CreatedBy\\\":\\\"c216cd34-6a3d-4f38-950b-ea3383a30a64\\\"}]\""
I have an object that matches this type called EventView and deserialize it into an object like so:
string result = "";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
JavaScriptSerializer jss = new JavaScriptSerializer();
JsonEventView ev = jss.Deserialize<JsonEventView>(result);
public class JsonEventView
{
public List<EventView> results { get; set; }
}
However, I get an error every time I attempt to deserialize it.
Cannot convert object of type 'System.String' to type 'EventManagerService.JsonEventView'
Web API handles the serialization for you. So you do not need to manually serialize the object to JSON.
return Request.CreateResponse(HttpStatusCode.OK, Active);
Of course, Web API being able to return JSON hinges on Content Negotiation and your app being properly configured, such that there is a formatter that can provide the output a consumer requests (JSON in this case).
Related
JsonDeserializer check before try to convert Model
Read simple api call code bellow. Here i am getting call response in- IRestResponse response and its a json response. Then using JsonDeserializer() i am trying to convert it to a C# Model which is WallMartData model. ( i think i dont need to share model code here bcoz it doesn't matter for this question ). Now from this same response sometime i will get a json response which match with my model WallMartData and some time it will return other json response. Now my question is- before i try to convert my json response to WallMartData Model i want to check if this is a valid convertable json. If its not valid convartable for this WallMartData model then it will skip try to convert. Bcoz when its fails to convert i am getting invalid json exception on c#. Thats why i need to check before try to convert. Any solution? string url = "http://api.example.com/v1/items?apiKey=" + Token + "&upc=" + UPC; var client = new RestClient(url); var request = new RestRequest(Method.GET); IRestResponse response = client.Execute(request); var deserializer = new JsonDeserializer(); var wmr = deserializer.Deserialize<WallMartData>(response);
You can try to create a method use try .... catch to check the JSON string is or isn't valid. private static bool IsValidJson<T>(string strInput,out T obj) { obj = default(T); try { obj = JsonConvert.DeserializeObject<T>(strInput); return true; } catch (JsonReaderException jex) { return false; } catch (Exception ex) { return false; } } Then you can use bool to check the DeserializeObject whether success. WallMartData wmr; if(IsValidJson<WallMartData>(response,out wmr)){ //... your logic with wmr }
I think you can just use try catch block and it will be enough. But if you really need to validate your JSON, you can use JSON Schema. You can generate schema for your class using JsonSchemaGenerator
I suggest using JsonSchema by Json.Net more info here let's say that your WallMartData class looks like this public class WallMartData { [JsonProperty("email", Required = Required.Always)] public string Email; [JsonProperty("first_name")] public string firstName; [JsonProperty("last_name")] public string lastName; } Then you can easily use the schema checker JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(WallMartData)); string json = #"..."; JObject wallMartData = JObject.Parse(json); if(wallMartData.IsValid(schema)) { //if json matching the schema aka the class account } else { //the json is invalid }
POST Web Service Client using C#
Can you please give me a sample example of how to make the JSON request body in C#. I am using Visual Studio 2015. I know SOAP UI, but I am new to C#. Thanks in advance.
You can try the following Lets assume you have the following webmethod public void Webmethod(string parameter) { //Do what ever } In C# you will do the following to call the webmethod, You require Json.net, Newtonsoft or other Json serializer var webRequest = WebRequest.Create("http:\\www.somesite.com/path/to/webservice/webservice.asmx/Webmethod"); webRequest.Method = "POST"; webRequest.ContentType = "application/json"; Build a Json object representing the parameters var jsonobjectrepresentingparameters = new {parameter = "Value"}; Get the Json string using Newtonsoft JsonConvert var datastring = Newtonsoft.Json.JsonConvert.SerializeObject(jsonobjectrepresentingparameters); Get the bytes var bytes = Encoding.ASCII.GetBytes(datastring); Write the bytes to the request var requestStream = webRequest.GetRequestStream(); requestStream.Write(bytes, 0,bytes.Length); Get repsonse var response = webRequest.GetResponse(); If your Webmethod returned anything like a string, int or other data you can use the following class to deserialize public class Type<T> { public T D { get; set; } public Type() { } } You will notice when you work with webservices it returns a json object with property d as the value which is why you require the above class in C# Then you will require the following extra two lines if your return type was string var json = (new StreamReader(response.GetResponseStream())).ReadToEnd(); var object = JsonConvert.DeserializeObject<Type<string>>(json);
Deserializing the object inside an http post
Hi I am trying to deserialize an Object from a HttpPost method call inside an authorize attribute.I am using ASP.NET Web Api Framework. Here is my code: public override void OnAuthorization(HttpActionContext actionContext) { var rezult = DeserializeStream<EvaluationFormDataContract>(actionContext.Request.Content.ReadAsStreamAsync().Result); } private T DeserializeStream<T>(Stream stream) { var binaryFormatter = new BinaryFormatter(); var rez = binaryFormatter.Deserialize(stream); var t = (T)binaryFormatter.Deserialize(stream); return t; } When this code gets executed I get this exception when the binaryFormatter tryes to deserialize it: The input stream is not a valid binary format. The starting contents (in bytes) are: 73-74-75-64-65-6E-74-41-73-73-69-67-6E-6D-65-6E-74 ... What am I doing wrong?
You are trying to use BinaryFormatter to binary deserialize data which was not binary serialized. From data you sent I see that hex code represents a string. 73-74-75-64-65-6E-74-41-73-73-69-67-6E-6D-65-6E-74 decoded is studentAssignment This leads me to believe you are doing a simple AJAX call and sending JSON data to WebAPI service. You need to deserialize the stream using JSON. Read request content as string If content is JSON, deserialize it using JSON.NET var json = actionContext.Request.Content.ReadAsStringAsync().Result; var m = JsonConvert.DeserializeObject<EvaluationFormDataContract>(json); If response is not JSON, but form data you can parse it like a query string. var stringData = actionContext.Request.Content.ReadAsStringAsync().Result; NameValueCollection data = HttpUtility.ParseQueryString(stringData); string personId = data["personId"];
using dynamic keyword when parse JSON
I'm newbie to using the dynamic keyword in C#. It seems simple enough, but I can't seem to use it effectively. I see this example from Facebook: var client = new FacebookClient(); dynamic me = client.Get("totten"); string firstname = me.first_name; it works fine, but if you look at me in a debugger, then you can see that client.Get() returns simple JSON. The same it's said in Facebook documentation: The result of this request is a dynamic object containing various properties such as first_name, last_name, user name, etc. You can see the values of this request by browsing to http://graph.facebook.com/totten in your web browser. The JSON result is shown below. I want to do the same dodge with returned JSON from Foursquare: private static string GetReturnedUrlFromHttp(string url) { HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; webRequest.Timeout = 10000; webRequest.Method = "GET"; WebResponse response = webRequest.GetResponse(); string responseStr = String.Empty; using (var stream = response.GetResponseStream()) { var r = new StreamReader(stream); responseStr = r.ReadToEnd(); } return responseStr; } public static void FillDataFromFoursquareUsingDynamic() { string foursquare_url_detail = "https://api.foursquare.com/v2/venues/4b80718df964a520e57230e3?locale=en&client_id=XXX&client_secret=YYY&v=10102013"; dynamic responseStr = GetReturnedUrlFromHttp(foursquare_url_detail); var response = responseStr.response; } I got the following error: 'string' does not contain a definition for 'response' Why am I getting this error and is it possible to 'parse' any JSON string like in Facebook?
FacebookClient.Get doesn't really return the JSON string. Instead it parses the string into a dynamic object with properties matching the names of the values in the JSON string. Using dynamic doesn't magically turn a string into an object with the properties defined in the string. Instead, you need to first parse the string with the help of a JSON library like JSON.NET.
how to split json format string in order to Deserialize is into .net object?
The subject sounds unclear, but the logic is very simple. I have a returned response data that is in json format. I want to Deserialize it into .net object which I defined already. I use JavaScriptSerializer class Deserialize method, it requires the parameter to be string. Now my response data is in json format, and has more than one roots. My code is WebRequest request = WebRequest.Create ("https://xxx.xxxxxx.com/xxxxx"); request.Method = "GET"; request.ContentType = "application/json"; var response = (HttpWebResponse)request.GetResponse(); using (var streamReader = new StreamReader(response.GetResponseStream())) { var responseText = streamReader.ReadToEnd(); } The responseText value is [ { "webinarKey":5303085652037254656, "subject":"Test+Webinar+One", "description":"Test+Webinar+One+Description", "organizerKey":73563532324, "times":[{"startTime":"2011-04-26T17:00:00Z","endTime":"2011-04-26T18:00:00Z"}] }, { "webinarKey":9068582024170238208, "name":"Test+Webinar+Two", "description":"Test Webinar Two Description", "organizerKey":73563532324, "times":[{"startTime":"2011-04-26T17:00:00Z","endTime":"2011-04-26T18:00:00Z"}] } ] I use following code to deserialize responseText to a .net object that I defined. JavaScriptSerializer ser = new JavaScriptSerializer(); Webinar w=ser.Deserialize<Webinar>(responseText); Error comes out says responseText is an array, not string. Then how to split responseText? I don't think it is appropriate to use string.split() method here.
Your response text is indeed a json array (containing 2 elements), as indicated by the [ and ] characters. Try the following: Webinar[] w=ser.Deserialize<Webinar[]>(responseText);
Have you tried: List<Webinar> w=ser.Deserialize<List<Webinar>>(responseText);?