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
Related
these are my classes.
public class BasketClass
{
public int HowMany { get; set; }
public int MBasketId { get; set; }
public int MVendorId { get; set; }
public int WInvestorId { get; set; }
public int MProductId { get; set; }
}
public class VendorPay
{
public int id { get; set; }
public int MVendorId { get; set; }
public bool IsCargoIncluded { get; set; }
public decimal CargoAmount { get; set; }
public decimal TotalAmount { get; set; }
}
public class PayBasketInputClass
{
public List<BasketClass> mOrderList { get; set; }
public List<VendorPay> vendorPayList { get; set; }
}
And this is my method.
public IActionResult PayBasket(int WInvestorId, PayBasketInputClass payInput, string paymenttype)
I gotta send payInput from body. But it includes two lists and its to complicated for me. Can you help me how to do it with an example?
Cheers.
{
"mOrderList": [
{
"HowMany": 1,
"MBasketId": 2,
"MVendorId": 3,
"WInvestorId": 4,
"MProductId": 5
}
],
"vendorPayList": [
{
"id": 1,
"MVendorId": 2,
"IsCargoIncluded": true,
"CargoAmount": 3.99,
"TotalAmount": 4.99
}
]
}
Json object is above is your PayBasketInputClass object in json structure.
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.
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; }
}
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.
I am working on a winform application that is going to communicate with a webstore API. When I try to get all products from the webstore they present me with the following JSON:
{
"code":200,
"data":{
"product_data":{
"122":{
"products_id":"122",
"products_name":"Camilla armchair",
"products_model":"",
"products_url":"http:\/\/mystore-demo.no\/products\/camilla-armchair",
"products_url_identifier":"camilla-armchair",
"products_sort_order":"0",
"products_quantity":"0",
"products_weight":"0",
"products_status":"1",
"products_price_ex_tax":"249.0000",
"products_tax_percentage":"25",
"products_description":"Beskrivelse Camilla armchair",
"products_date_added":"2011-10-12 15:32:06",
"products_last_modified":"2011-10-12 15:32:06",
"products_brand_name":"",
"products_brand_id":"0",
"products_categories":[
"42",
"44"
],
"products_attributes":[
],
"products_tabs":[
],
"products_images":[
"http:\/\/mystore-demo.no\/users\/demo_mystore_no\/images\/122_Camilla_armchair_1.jpg"
],
"products_index": "2"
},
"123":{
"products_id":"123",
"products_name":"Egg Chair",
"products_model":"",
"products_url":"http:\/\/mystore-demo.no\/products\/egg-chair",
"products_url_identifier":"egg-chair",
"products_sort_order":"0",
"products_quantity":"0",
"products_weight":"0",
"products_status":"1",
"products_price_ex_tax":"2999.0000",
"products_tax_percentage":"25",
"products_description":"Beskrivelse Egg Chair",
"products_date_added":"2011-10-12 15:33:27",
"products_last_modified":"2011-10-12 15:33:27",
"products_brand_name":"",
"products_brand_id":"0",
"products_categories":[
"42"
],
"products_attributes":[
],
"products_tabs":[
],
"products_images":[
"http:\/\/mystore-demo.no\/users\/demo_mystore_no\/images\/123_Egg_Chair_1.jpg"
],
"products_index": "3"
},
"121":{
"products_id":"121",
"products_name":"Round chair",
"products_model":"",
"products_url":"http:\/\/mystore-demo.no\/products\/round-chair",
"products_url_identifier":"round-chair",
"products_sort_order":"0",
"products_quantity":"0",
"products_weight":"0",
"products_status":"1",
"products_price_ex_tax":"1599.0000",
"products_tax_percentage":"25",
"products_description":"Beskrivelse Round Chair",
"products_date_added":"2011-10-11 10:43:42",
"products_last_modified":"2011-10-11 10:43:42",
"products_brand_name":"",
"products_brand_id":"0",
"products_categories":[
"42"
],
"products_attributes":[
],
"products_tabs":[
],
"products_images":[
"http:\/\/mystore-demo.no\/users\/demo_mystore_no\/images\/121_Round_chair_1.jpg"
]
,
"products_index": "1"
}
},
"product_count_total":3
}
}
I have created a MyStoreResponse class (datamodel) that looks like this:
using Newtonsoft.Json;
namespace MyStoreSync.Models
{
public class Product
{
[JsonProperty("products_id")]
public string ProductsId { get; set; }
[JsonProperty("products_name")]
public string ProductsName { get; set; }
[JsonProperty("products_model")]
public string ProductsModel { get; set; }
[JsonProperty("products_url")]
public string ProductsUrl { get; set; }
[JsonProperty("products_url_identifier")]
public string ProductsUrlIdentifier { get; set; }
[JsonProperty("products_sort_order")]
public string ProductsSortOrder { get; set; }
[JsonProperty("products_quantity")]
public string ProductsQuantity { get; set; }
[JsonProperty("products_weight")]
public string ProductsWeight { get; set; }
[JsonProperty("products_status")]
public string ProductsStatus { get; set; }
[JsonProperty("products_price_ex_tax")]
public string ProductsPriceExTax { get; set; }
[JsonProperty("products_tax_percentage")]
public string ProductsTaxPercentage { get; set; }
[JsonProperty("products_description")]
public string ProductsDescription { get; set; }
[JsonProperty("products_date_added")]
public string ProductsDateAdded { get; set; }
[JsonProperty("products_last_modified")]
public string ProductsLastModified { get; set; }
[JsonProperty("products_brand_name")]
public string ProductsBrandName { get; set; }
[JsonProperty("products_brand_id")]
public string ProductsBrandId { get; set; }
[JsonProperty("products_categories")]
public string[] ProductsCategories { get; set; }
[JsonProperty("products_attributes")]
public object[] ProductsAttributes { get; set; }
[JsonProperty("products_tabs")]
public object[] ProductsTabs { get; set; }
[JsonProperty("products_images")]
public string[] ProductsImages { get; set; }
[JsonProperty("products_index")]
public string ProductsIndex { get; set; }
}
public class ProductData
{
[JsonProperty("Product")]
public Product Product { get; set; }
}
public class Data
{
[JsonProperty("product_data")]
public ProductData ProductData { get; set; }
[JsonProperty("product_count_total")]
public int ProductCountTotal { get; set; }
}
public class MyStoreResponse
{
[JsonProperty("code")]
public int Code { get; set; }
[JsonProperty("data")]
public Data Data { get; set; }
}
}
I get the correct ProductCountTotal, but Product is always null. Can anyone with more knowledege about parsing JSON help me?
You need to make the ProductData property be a dictionary:
public class Data
{
[JsonProperty("product_data")]
public Dictionary<string, Product> ProductData { get; set; }
[JsonProperty("product_count_total")]
public int ProductCountTotal { get; set; }
}
The ProductData class is unnecessary. The JSON property names "122", "123" and "121" become the dictionary keys, and the associated Product the value. See Serialize a Dictionary.
You are having this problem because "product" isn't a key in the json returned, in your ProductData class the key is named "product", but "121", "122" and "123" represent products...
You could do the Product serialization like this:
foreach(var x in productDataInstance)
{
Product p = JsonConvert.Deserialize(x);
}
Also, I think ProductData should have a list of Products.
public class ProductData
{
public List<Product> products = new List<Products>();
}
We'll now have:
foreach(var x in productDataInstance)
{
Product p = JsonConvert.Deserialize(x);
productDataInstance.products.Add(p);
}
NB productDataInstance is ProductData in your Data class.
Hope this helped.