I'm using JSON.Net to try and deserialize some responses from facebook. Here's a snapshot of the data I'm reading in:
{
"data": [
{
"id": "123"
},
{
"id": "234"
}
],
"paging": {
"cursors": {
"before": "xxx",
"after": "xxx"
},
"next": "xxx"
}
}
classes:
class jsonDeserialize
{
public List<ListDetail> ListDetail { get; set; }
}
public class DataList
{
public string id { get; set; }
}
public class Paging
{
public List<string> cursors { get; set; }
public string next { get; set; }
}
public class Cursors
{
public string before { get; set; }
public string after { get; set; }
}
public class ListDetail
{
public List<Cursors> Cursors { get; set; }
public List<Paging> Articles { get; set; }
public List<DataList> DataList { get; set; }
}
I'm using this code to use the JSON.NET Deserialize function:
for some reason, result return null, please help me :(
var result = JsonConvert.DeserializeObject<jsonDeserialize>(jsonString);
Fix your classes defenition:
class jsonDeserialize
{
public List<DataList> data { get; set; }
public Paging paging { get; set; }
}
public class DataList
{
public string id { get; set; }
}
public class Paging
{
public Cursors cursors { get; set; }
public string next { get; set; }
}
public class Cursors
{
public string before { get; set; }
public string after { get; set; }
}
jsonDeserialize contains list of DataList, ListDetail can me removed, cursors is not an array, it's an object.
Omg, I've missed it is JSON from facebook and "solved" reversed problem. I'll keep it here, though, just in case
First, as quick remark, your deserialization code here must look smth like var result = JsonConvert.DeserializeObject<jsonDeserialize>(jsonString);
Your JSON does not correspond to code.
If you want deserialize to jsonDeserialize class your json must look like that
(pay close attention to [] and {})
{
"ListDetail" :
[
{
"Cursors":
[
{
"before" : "value",
"after" : "value"
}
],
"Articles":
[
{
"Cursors":
[
"cursor1",
"cursor2"
],
"next" : "somenext"
}
],
"DataList":
[
{
"id" : "someid"
},
{
"id" : "someid2"
}
]
}
]
}
class jsonDeserialize
{
public List<DataList> data { get; set; }
public Paging paging { get; set; }
}
public class DataList
{
public string id { get; set; }
}
public class Paging
{
public Cursors cursors { get; set; }
public string next { get; set; }
}
public class Cursors
{
public string before { get; set; }
public string after { get; set; }
}
var result=JsonConvert.DeserializeObject<jsonDeserialize>(jsonformat.Substring(0,jsonformat.Length));
Use it it will give you write result. beacuse data and paging treated as properties so that you need to intialize those properties in your class jsondeserailized and instead of list use cursors because you storing cursors data in paging class .Thanks
Related
I will create a C# Model, but I am not sure, what is the best way to do it. Maybe you can help me.
It is about a query of customer data.
Graphically it looks like this. Our customer can design the request very individually. He can link all fields that exist with one another
And the json object to my controller is like this.
{
"predicates":[
{
"type":"role",
"attribute":"role",
"comparison":"eq",
"value":"user_role"
},
{
"type":"and",
"predicates":[
{
"type":"or",
"predicates":[
{
"type":"boolean",
"attribute":"custom_data.has_paid",
"comparison":"unknown",
"value":null
},
{
"type":"boolean",
"attribute":"custom_data.has_paid",
"comparison":"false",
"value":null
}
]
},
{
"type":"string",
"attribute":"custom_data.plan_aktiv",
"comparison":"eq",
"value":"freeMember"
},
{
"type":"date",
"attribute":"custom_data.ipnFree_ends",
"comparison":"gt",
"value":"30"
},
{
"type":"integer",
"attribute":"session_count",
"comparison":"gt",
"value":"15"
}
]
}
],
"segment_id":"61697d1fc753cca611bf7034",
"page":1,
"per_page":25,
"sort_by":"remote_created_at",
"sort_direction":"desc"
}
My idea of the model is following
public class Predicate
{
public string type { get; set; }
public string attribute { get; set; }
public string comparison { get; set; }
public string value { get; set; }
public List<Predicate> predicates { get; set; }
}
public class Root
{
public List<Predicate> predicates { get; set; }
public string segment_id { get; set; }
public int page { get; set; }
public int per_page { get; set; }
public string sort_by { get; set; }
public string sort_direction { get; set; }
}
But I am not sure, if its the best model for all querys. What do you mean? Thanks for your help
Do you need more information about that case?
I have the following section of JSON coming from Shopify:
{
"orders": [
{
"total_line_items_price_set": {
"shop_money": {
"amount": "281.96",
"currency_code": "USD"
},
"presentment_money": {
"amount": "281.96",
"currency_code": "USD"
}
},
"total_discounts_set": {
"shop_money": {
"amount": "0.00",
"currency_code": "USD"
},
"presentment_money": {
"amount": "0.00",
"currency_code": "USD"
}
},
},
When I utilize the Paste JSON as Classes feature I am getting elements like "shop_money" and "presentment_money" repeated and numbered as individual classes.
public class Total_Line_Items_Price_Set
{
public Shop_Money shop_money { get; set; }
public Presentment_Money presentment_money { get; set; }
}
public class Shop_Money
{
public string amount { get; set; }
public string currency_code { get; set; }
}
public class Presentment_Money
{
public string amount { get; set; }
public string currency_code { get; set; }
}
public class Total_Discounts_Set
{
public Shop_Money1 shop_money { get; set; }
public Presentment_Money1 presentment_money { get; set; }
}
public class Shop_Money1
{
public string amount { get; set; }
public string currency_code { get; set; }
}
public class Presentment_Money1
{
public string amount { get; set; }
public string currency_code { get; set; }
}
I'm new to JSON and how it should be represented as classes in C# - this seems wrong. Is it possible to get a better result?
SOLUTION:
Based on the answer by Zakk Diaz I removed each class that was duplicated and numbered. Having done so I am successfully deserializing and making use of an array of order objects.
public class Orders
{
public Order[] orders { get; set; }
}
public class Order
{
// [...]
}
class Program
{
static void Main(string[] args)
{
// [...]
Orders testOrders = JsonConvert.DeserializeObject<Orders>(responseFromServer);
Console.WriteLine(testOrders.orders[0].id);
Console.WriteLine(testOrders.orders[0].total_line_items_price_set.shop_money.amount);
Console.WriteLine(testOrders.orders[0].line_items[1].price_set.shop_money.amount);
}
}
It looks fine for the most part, you can delete these classes and rename them in "Total_Discounts_Set"
public class Shop_Money1
{
public string amount { get; set; }
public string currency_code { get; set; }
}
public class Presentment_Money1
{
public string amount { get; set; }
public string currency_code { get; set; }
}
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; }
}
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.
I'm using C# to parse a web API that returns a JSON data.
{
"response": {
"success": 1,
"items": {
"Items 1's name": {
"index": [
1
],
"data": {
"1": {
"special1": {
"special2": [
{
"value": "4 usd"
}
]
}
}
}
}
}
}
}
I have managed to parse "response" to "success" part using
public class ResponseResult {
[JsonProperty("response")]
public bpResponse Response { get; set; }
}
public class bpResponse {
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("items")]
public Item items { get; set; }
}
using (var jr = new JsonTextReader(new StringReader(data))) {
var js = new JsonSerializer();
var u = js.Deserialize<ResponseResult>(jr);
Console.WriteLine(u.Response.Current_Time);
}
And I'm stuck after this as I realized that for the item's name, there is no key available. Can some one guide me on how to continue parsing the data?
Thanks in advance!
Let's assume that you have valid JSON, then you can deserialize it using next structure:
public class ResponseResult
{
[JsonProperty("response")]
public bpResponse Response { get; set; }
}
public class bpResponse
{
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("items")]
public Item Items { get; set; }
}
public class Item
{
[JsonProperty("Items 1's name")]
public ItemFirstName ItemFirstName { get; set; }
}
public class ItemFirstName
{
[JsonProperty("index")]
public List<string> Index { get; set; }
[JsonProperty("data")]
public Data Data { get; set; }
}
public class Data
{
[JsonProperty("1")]
public First First { get; set; }
}
public class First
{
[JsonProperty("special1")]
public Special1 Special1 { get; set; }
}
public class Special1
{
[JsonProperty("special2")]
public List<Special2> Special2 { get; set; }
}
public class Special2
{
[JsonProperty("value")]
public string Value { get; set; }
}