C# Deserialize without key - c#

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; }
}

Related

How to bind this json and read specific key value

I have below json which I would like to read it in a list. below are the classes and model defined and the code by which I am trying to read. I am getting null value on binding. I am not sure how should i achieve this. So for example if I have multiple rules, I would like to read each one based on the condition passed. Please see my last sample code for better understanding.
Sample Json:
{"TableStorageRule": { "Rules": [ {
"Name": "filterRule1",
"DataFilter":
{
"DataSetType": "Settings1"
},
"TableSettings":
{
"AzureTable": {
"Account": "account1",
"Table": "table1",
"Key": "key1"
},
"SchemaBaseUri": "https://test.web.core.windows.net/"
}
},
{
"Name": "filterRule2",
"DataFilter":
{
"DataSetType": "Settings2"
},
"TableSettings":
{
"AzureTable": {
"Account": "account2",
"Table": "table2",
"Key": "key2"
},
"SchemaBaseUri": "https://test2.web.core.windows.net/"
}
}
] }}
Model and Code:
public class TableStoreSettings
{
public class AzureTableSettings
{
public string Account { get; set; }
public string Key { get; set; }
public string Table { get; set; }
}
public AzureTableSettings AzureTable { get; set; }
public Uri SchemaBaseUri { get; set; }
}
public class TableStorageRule
{
public string Name { get; set; }
public TwisterDataFilter DataFilter { get; set; }
public TableStoreSettings TableSettings { get; set; }
}
public class TableStorageConfiguration
{
public IEnumerable<TableStorageRule> Rules { get; set; } = new List<TableStorageRule>();
}
code by which I am trying to read:
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(Root))
.AddJsonFile("appsettings.json", optional: false);
var config = builder.Build();
var tableStorageOutput = new TableStorageRule();
config.GetSection("TableStorageRule").Bind(tableStorageOutput);
var nameOfFilter = tableStorageOutput.Name;
if (tableStorageOutput.Name == "filterRule1")
{
var accountname = tableStorageOutput.TableSettings.AzureTable.Account;
}
on above I only get first filtername1 , i dont get other filternames and so on...though on GetSection() i see all the values in quick watch.
this is correct models from your JSON file :
public class DataFilter {
public string DataSetType { get; set; }
}
public class AzureTable {
public string Account { get; set; }
public string Table { get; set; }
public string Key { get; set; }
}
public class TableSettings {
public AzureTable AzureTable { get; set; }
public string SchemaBaseUri { get; set; }
}
public class Rule {
public string Name { get; set; }
public DataFilter DataFilter { get; set; }
public TableSettings TableSettings { get; set; }
}
public class TableStorageRule {
public List<Rule> Rules { get; set; }
}
public class Root {
public TableStorageRule TableStorageRule { get; set; }
}
for test you can read your JSON file and get values (maybe change models solve your problem in your code):
string json = File.ReadAllText(jsonFilePath);
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(json);

Paste JSON as Classes Duplicates and Numbers Elements as Unique Classes

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; }
}

How to create a treeview in c# when Deserialize Json to object?

I'm new into c# and wpf. i have successful deserialize the json data into object by using restsharp.
Currently my json data returns when call a GET method has something looks like this:
{
"elements":[
{
"id":1,
"subject":"New website",
"_links":{
"children":[
{
"href":"/api/v3/work_packages/6",
"title":"New landing page"
},
{
"href":"/api/v3/work_packages/4",
"title":"Newsletter registration form"
},
{
"href":"/api/v3/work_packages/5",
"title":"Implement product tour"
}
]
}
},
{
"id":6,
"subject":"New landing page",
"_links":{
"ancestors":[
{
"href":"/api/v3/work_packages/3",
"title":"New website"
}
]
}
}
]
}
and more
So my question is that how to put it into a treeview template?
public class Outer
{
public List<RootObjectForAncestor> elements { get; set; }
public List<RootObjectForChild> elements { get; set; }
}
public class RootObjectForAncestor
{
public string id { get; set; }
public string subject { get; set; }
public LinksChild _links { get; set; }
}
public class LinksChild
{
public List<Child> children { get; set; }
}
public class Child
{
public string href { get; set; }
public string title { get; set; }
}
####and this below for the child class #####
public class RootObjectForChild
{
public int id { get; set; }
public string subject { get; set; }
public LinksAncestor _links { get; set; }
}
public class Ancestor
{
public string href { get; set; }
public string title { get; set; }
}
public class LinksAncestor
{
public List<Ancestor> ancestors { get; set; }
}
My function for getting normal get method looks like this
var client = new RestClient("my endpoint");
client.Authenticator = newHttpBasicAuthenticator("apikey","myapikey");
var request = new RestSharp.RestRequest("api/v3/projects/1/work_packages", Method.GET);
IRestResponse response = client.Execute(request);
var obj = JsonConvert.DeserializeObject<Outer>(response.Content);
So the question is how do i put these binding into the treeview?

Serializing Json to c# Class throwing error

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; }
}

Json.net DeserializeObject issue

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

Categories