Serializing Json to c# Class throwing error - c#

I have a JSON returning from web like this
{
"data": {
"normal_customer": {
"0": {
"id": 1,
"name": "ALPHY"
}
},
"1": {
"id": 2,
"name": "STEVEN"
}
},
"luxury_customer": {
"3": {
"id": 8,
"name": "DEV"
}
}
}
}
I have created c# classes
public class StandardCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
public class LuxuryCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class Data
{
public StandardCustomers standard_Customers { get; set; }
public LuxuryCustomers luxury_Customers { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
}
When I use deserialize the response from the website using below c# code
var result1 = JsonConvert.DeserializeObject<Data>(response);
but result1.luxury_customers contains customerdetails which is null.
As suggested by #hellostone, I have modified to rootdata, then also
result1.luxury_customers contains customerdetails is null.
Any idea how to deserialize to c# class
When we pasted Json to visual studio, it generated classes as below
public class Rootobject
{
public Data data { get; set; }
}
public class Data
{
public Standard_Customers standard_Customers { get; set; }
public Luxury_Customers luxury_Customers { get; set; }
}
public class Standard_Customers
{
public _0 _0 { get; set; }
public _1 _1 { get; set; }
public _2 _2 { get; set; }
public _4 _4 { get; set; }
public _5 _5 { get; set; }
}
public class _0
{
public int id { get; set; }
public string name { get; set; }
}
individual classes are generated in standard customers , can we use list for this

I guess the problem is that index in luxury_customers starting not from zero. Try to use Dictionary<string,CustomersDetails> in LuxuryCustomers instead List<CustomersDetails>.
I've managed to deserialize Json with this classes:
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
}
public class Data
{
public Dictionary<string, CustomersDetails> normal_customer { get; set; }
public Dictionary<string,CustomersDetails> luxury_customer { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
Deserialization code:
var result = JsonConvert.DeserializeObject<RootObject>(text);
P.S. I've remove one closing bracket after "ALPHY" element, to make Json valid, I hope it was typo and you're getting valid Json.

Your json string doesn't match with your defined classes. Your Json string should look like this if you want to preserve your class structure:
{
"data":{
"standard_Customers":{
"Customers_Details":[
{
"id":1,
"name":"ALPHY"
},
{
"id":2,
"name":"STEVEN"
}
]
},
"luxury_Customers":{
"Customers_Details":[
{
"id":8,
"name":"DEV"
}
]
}
}
}
Pay attention to the square brackets at the "Customers_Details" attribute.
Then the:
var result1 = JsonConvert.DeserializeObject<RootObject>(response);
call, will give you the right object back and it shouldn't be null, when using your class structure:
public class StandardCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
}
public class LuxuryCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class Data
{
public StandardCustomers standard_Customers { get; set; }
public LuxuryCustomers luxury_Customers { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}

Related

Parse a json generated by jstree in C#

I'm currently receiving the following string of an array that was generated from JsTree:
"[
{
"id":"j1_1",
"text":"Root node 1",
"icon":true,
"li_attr":{
"id":"j1_1"
},
"a_attr":{
"href":"#",
"id":"j1_1_anchor"
},
"data":{
},
"children":[
{
"id":"j1_2",
"text":"Child 1",
"icon":true,
"li_attr":{
"id":"j1_2"
},
"a_attr":{
"href":"#",
"id":"j1_2_anchor"
},
"data":{
},
"children":[
]
}
]
}
]"
I'm trying to deserialize the following item by using
JsTreeModel aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<JsTreeModel>(json);
With JsTreeModel being this class:
public class JsTreeModel
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("text")]
public string text { get; set; }
[JsonProperty("icon")]
public string icon { get; set; }
[JsonProperty("li_attr")]
public string li_attr { get; set; }
[JsonProperty("a_attr")]
public string a_attr { get; set; }
[JsonProperty("data")]
public string data { get; set; }
}
But I'm getting the error`:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'AccesosWeb.Entidad.JsTree.JsTreeModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
I think the issue is with how the class is structured, but I don't know how to build it.
This is the model you need in consideration of the json you paste:
You can use the main object:
JsTreeModel myDeserializedClass = JsonConvert.DeserializeObject<JsTreeModel>(json);
and the object is:
public class JsTreeModel
{
public List<MyArray> MyArray { get; set; }
}
public class LiAttr
{
public string id { get; set; }
}
public class AAttr
{
public string href { get; set; }
public string id { get; set; }
}
public class Data
{
}
public class Child
{
public string id { get; set; }
public string text { get; set; }
public bool icon { get; set; }
public LiAttr li_attr { get; set; }
public AAttr a_attr { get; set; }
public Data data { get; set; }
public List<object> children { get; set; }
}
public class MyArray
{
public string id { get; set; }
public string text { get; set; }
public bool icon { get; set; }
public LiAttr li_attr { get; set; }
public AAttr a_attr { get; set; }
public Data data { get; set; }
public List<Child> children { get; set; }
}

C# Unit Testing - Assertions on JSON

I am just playing around with some Json and Fluentassertions, I am able to make a call to an API successfully, get the results, deserialize them but for some reason when i get to do an assertion on the response its losing the data and it empty. I have debugged, can see the data flowing through and then losing it during assertion.
Any help appreciated.
{
[TestClass]
public class UnitTest1
{
HttpClient client = new HttpClient();
[TestMethod]
public void ActorNotInSeason6Episode1()
{
try
{
//test = extent.CreateTest("Test 1");
HttpResponseMessage respone = client.GetAsync("https://api.themoviedb.org/3/tv/1399/season/6/episode/1/credits?api_key=").Result;
Assert.IsTrue(respone.IsSuccessStatusCode.Equals(true));
string ResponseMessage = respone.Content.ReadAsStringAsync().Result;
Actors actors = JsonConvert.DeserializeObject<Actors>(ResponseMessage);
//var a = Actors.cast["cast"];
//var names = a.Children[];
//var a = actors.cast.Children();
actors.cast.Should().Contain("Emilia Clarke", "Test");
}
catch(AssertFailedException)
{
Assert.Fail();
}
}
}
}
class Actors
{
public JArray cast { get; set; }
public JArray guest_stars { get; set; }
}
}
JSON
{[
{
"character": "Daenerys Targaryen",
"credit_id": "5256c8af19c2956ff60479f6",
"gender": 1,
"id": 1223786,
"name": "Emilia Clarke",
"order": 0,
"profile_path": "/lRSqMNNhPL4Ib1hAJxmDFBXHAMU.jpg"
}
]}
Here is fluentassertions extension for JSON, which contains many useful methods for asserting JSON:
Available extension methods
BeEquivalentTo()
ContainSingleElement()
ContainSubtree()
HaveCount()
HaveElement()
HaveValue()
MatchRegex()
NotBeEquivalentTo()
NotHaveElement()
NotHaveValue()
NotMatchRegex()
I am not an author of this library.
Using the following strongly typed definitions based on the expected JSON from themoviedb
public partial class RootObject {
[JsonProperty("cast")]
public Cast[] Cast { get; set; }
[JsonProperty("crew")]
public Crew[] Crew { get; set; }
[JsonProperty("guest_stars")]
public Cast[] GuestStars { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
}
public partial class Cast {
[JsonProperty("character")]
public string Character { get; set; }
[JsonProperty("credit_id")]
public string CreditId { get; set; }
[JsonProperty("gender")]
public long Gender { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("order")]
public long Order { get; set; }
[JsonProperty("profile_path")]
public string ProfilePath { get; set; }
}
public partial class Crew {
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("credit_id")]
public string CreditId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("department")]
public string Department { get; set; }
[JsonProperty("job")]
public string Job { get; set; }
[JsonProperty("gender")]
public long Gender { get; set; }
[JsonProperty("profile_path")]
public string ProfilePath { get; set; }
}
You would need to do the following in your test
//...
var actors = JsonConvert.DeserializeObject<RootObject>(ResponseMessage);
//Assert
actors.Cast.Should().Contain(actor => actor.Name == "Emilia Clarke");

Invalid type when generate the json?

I've this json:
{
"page": "36",
"bookmaker_urls": {
"13": [{
"link": "http://www.bet365.com/home/?affiliate=365_179024",
"name": "Bet 365"
}]
},
"block_service_id": "competition_summary_block_competitionmatchessummary",
"round_id": "36003",
"outgroup": "",
"view": "1",
"competition_id": "13"
}
I've inserted this on this tool: http://json2csharp.com/
this will return:
public class __invalid_type__13
{
public string link { get; set; }
public string name { get; set; }
}
public class BookmakerUrls
{
public List<__invalid_type__13> __invalid_name__13 { get; set; }
}
public class RootObject
{
public int page { get; set; }
public BookmakerUrls bookmaker_urls { get; set; }
public string block_service_id { get; set; }
public int round_id { get; set; }
public bool outgroup { get; set; }
public int view { get; set; }
public int competition_id { get; set; }
}
why there is an invalid type?
13 is not a valid property name in .NET, and the tool you're using seems to try to map each JSON property to .NET Class property.
What you probably want is bookmaker_urls to be a dictionary:
public class BookmakerUrl
{
public string link { get; set; }
public string name { get; set; }
}
public class RootObject
{
public int page { get; set; }
public Dictionary<string, List<BookmakerUrl>> bookmaker_urls { get; set; }
public string block_service_id { get; set; }
public int round_id { get; set; }
public bool outgroup { get; set; }
public int view { get; set; }
public int competition_id { get; set; }
}
The generator generates the name of properties and types from the name of properties in the Json.
There is a property "13" in the Json. A name starting with a digit would not be a valid name in c#.
So, the generator just adds the prefix "invalid_name" or "invalid_type" to the generated names. This does not mean that there was any problem or that you cannot use the generated code.

processing api output in vb.net or c#

After making an api call, the example below shows what a typical response would be.
{
"code":"success",
"message":"Data retrieved for email",
"data":{
"attributes":{
"EMAIL":"example#example.net",
"NAME" : "Name",
"SURNAME" : "surname"
},
"blacklisted":1,
"email":"example#example.net",
"entered":"2014-01-15",
"listid":[8],
"message_sent":[{
"camp_id" : 2,
"event_time" : "2013-12-18"
},
{ "camp_id" : 8,
"event_time" : "2014-01-03"
},
{ "camp_id" : 11,
"event_time" : "2014-01-07"
}],
"hard_bounces":[{
"camp_id" : 11,
"event_time" : "2014-01-07"
}],
"soft_bounces":[],
"spam":[{
"camp_id" : 2,
"event_time" : "2014-01-09"
}],
"unsubscription":{
"user_unsubscribe":[
{
"event_time":"2014-02-06",
"camp_id":2,
"ip":"1.2.3.4"
},
{
"event_time":"2014-03-06",
"camp_id":8,
"ip":"1.2.3.4"
}
],
"admin_unsubscribe":[
{
"event_time":"2014-04-06",
"ip":"5.6.7.8"
},
{
"event_time":"2014-04-16",
"ip":"5.6.7.8"
}
]
},
"opened":[{
"camp_id" : 8,
"event_time" : "2014-01-03",
"ip" : "1.2.3.4"
}],
"clicks":[],
"transactional_attributes":[
{
"ORDER_DATE":"2015-07-01",
"ORDER_PRICE":100000,
"ORDER_ID":"1"
},
{
"ORDER_DATE":"2015-07-05",
"ORDER_PRICE":500000,
"ORDER_ID":"2"
}
],
"blacklisted_sms":1
}
}
What I need to do is to be able to read / find and attribute name and its corresponding value. I also need to know the value of blacklisted.
I don't know how to interpret the output given to easily find and read attributes and their values and also get the value of blacklisted.
Maybe if I can get it into an array, I can cycle through the array to find the value pair I am looking for? Or maybe I am overthinking it and their is an easier way.
Please note: This example only shows 3 attribute:value pairs. other calls may output more than three attribute:value pairs.
The simplest way is: You are getting the response in the JSON format and you just need it to be seralized with the use of classes and Json.NET
public class Rootobject
{
public string code { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
public class Data
{
public Attributes attributes { get; set; }
public int blacklisted { get; set; }
public string email { get; set; }
public string entered { get; set; }
public int[] listid { get; set; }
public Message_Sent[] message_sent { get; set; }
public Hard_Bounces[] hard_bounces { get; set; }
public object[] soft_bounces { get; set; }
public Spam[] spam { get; set; }
public Unsubscription unsubscription { get; set; }
public Opened[] opened { get; set; }
public object[] clicks { get; set; }
public Transactional_Attributes[] transactional_attributes { get; set; }
public int blacklisted_sms { get; set; }
}
public class Attributes
{
public string EMAIL { get; set; }
public string NAME { get; set; }
public string SURNAME { get; set; }
}
public class Unsubscription
{
public User_Unsubscribe[] user_unsubscribe { get; set; }
public Admin_Unsubscribe[] admin_unsubscribe { get; set; }
}
public class User_Unsubscribe
{
public string event_time { get; set; }
public int camp_id { get; set; }
public string ip { get; set; }
}
public class Admin_Unsubscribe
{
public string event_time { get; set; }
public string ip { get; set; }
}
public class Message_Sent
{
public int camp_id { get; set; }
public string event_time { get; set; }
}
public class Hard_Bounces
{
public int camp_id { get; set; }
public string event_time { get; set; }
}
public class Spam
{
public int camp_id { get; set; }
public string event_time { get; set; }
}
public class Opened
{
public int camp_id { get; set; }
public string event_time { get; set; }
public string ip { get; set; }
}
public class Transactional_Attributes
{
public string ORDER_DATE { get; set; }
public int ORDER_PRICE { get; set; }
public string ORDER_ID { get; set; }
}
Use Newtonsoft.Json library. One of the most powerful library.Parse your JSON to strongly typed C# object using json2csharp.com then just deserialize the string.
var model= JsonConvert.DeserializeObject<Classname>(result);
You'll need JSON.Net. Pasrse your JSON to strongly typed C# object using json2csharp.com then just deserialize the string using JsonConvert.Deserialize<RootObject>().
One way would be to:
a) Copy your JSON to Clipboard (CTRL+C)
b) On a Visual Studio class, click on EDIT-> Paste Special -> Paste JSON as classes. This will create the classes equivalent of your JSON for you. Your main object would be named as "Rootobject" and you can change this to whatever name you want.
c) Add System.Web.Extensions to your references
d) You can convert your JSON to class like so:
JavaScriptSerializer serializer = new JavaScriptSerializer();
Rootobject rootObject = serializer.Deserialize<Rootobject>(JsonString);
Where JsonString is your API output.

Convert json into class

I need to create clasess from json, but found some strange part that really troubles me. This is example from documentation that i have to response to them. There is some "Fenway Room" that should be variable but it looks it is value (room name) that contain other properties.
{
"api_version" : 4 ,
"hotel_ids" : [97497],
"num_hotels" : 1,
"hotels" :
[
{
"hotel_id": 97497,
"room_types":
{
"Fenway Room":
{
"url": "",
"price": 178,
"fees": 80,
"fees_at_checkout": 0,
"taxes": 20,
"taxes_at_checkout": 0,
"final_price": 278
}
}
}
]
}
here are classes online generated, and looks wrong. it looks that is not possible.
public class FenwayRoom
{
public string url { get; set; }
public int price { get; set; }
public int fees { get; set; }
public int fees_at_checkout { get; set; }
public int taxes { get; set; }
public int taxes_at_checkout { get; set; }
public int final_price { get; set; }
}
public class RoomTypes
{
public FenwayRoom __invalid_name__Fenway Room { get; set; }
}
public class Hotel
{
public int hotel_id { get; set; }
public RoomTypes room_types { get; set; }
}
public class RootObject
{
public int api_version { get; set; }
public List<int> hotel_ids { get; set; }
public int num_hotels { get; set; }
public List<Hotel> hotels { get; set; }
}
This is my first working with json, so im really confused. Json looks valid, but it is possible to create classes from that or i should create response manualy?... joining strings...
added example:
"hotels" :[
{
"hotel_id" : 258705 ,
"room_types" :
{
"Room 1" :
{
"url" :"", "price" : 1136 , "fees" : 101.55 , "taxes" : 50.00 , "final_price" : 1287.55 ,
}
"Room 2" :
{
"url" :"", "price" : 1136 , "fees" : 101.55 , "taxes" : 50.00 , "final_price" : 1287.55 ,
}
}
}
]
Where "Room 1" and "Room 2" are room titles, not properties or variables... it can be anything here.
This works with ASP.NET MVC4. I don't know if lower supports it.
public JsonResult MyAPI()
{
return Json(new RootObject { api_version = 1,
hotel_ids = 12342,
hotels = new Hotel{ hotel_id = 123,
room_types = new RoomTypes...
}
}
}
As far as Json is an object herited from the class Controller.
You can generate classes from json by creating a new class, copying the json out, go to Edit->paste special->paste json as classes
Then you will get this:
class Class1
{
public class Rootobject
{
public int api_version { get; set; }
public int[] hotel_ids { get; set; }
public int num_hotels { get; set; }
public Hotel[] hotels { get; set; }
}
public class Hotel
{
public int hotel_id { get; set; }
public Room_Types room_types { get; set; }
}
public class Room_Types
{
public FenwayRoom FenwayRoom { get; set; }
}
public class FenwayRoom
{
public string url { get; set; }
public int price { get; set; }
public int fees { get; set; }
public int fees_at_checkout { get; set; }
public int taxes { get; set; }
public int taxes_at_checkout { get; set; }
public int final_price { get; set; }
}
}
try this one out
http://json2csharp.com/
http://json2csharp.com/
Paste your Json String there it will generate the Json Class

Categories