Nested Json Convert to Class C# - c#

I am needing the first item in the array of object b in this json.
{
"error":[],
"result":{
"XXRPXXBT":{
"a":[
"0.000084280",
"123",
"123.000"
],
"b":[
"0.000084120",
"24263",
"24263.000"
],
"c":[
"0.000084140",
"772.40225814"
],
"v":[
"1002684.00590349",
"1081301.61838716"
],
"p":[
"0.000085783",
"0.000085799"
],
"t":[
731,
866
],
"l":[
"0.000083420",
"0.000083420"
],
"h":[
"0.000086610",
"0.000086720"
],
"o":"0.000086300"
}
}
}
Could someone please tell me how the class properties would look to get to that level. I have tried a json deserialization with a string for result but it fails on the convert.
I don't have to have all the values just the first item in the b array.
This is what I had done:
TestResponse deserializedKrakenResult = JsonConvert.DeserializeObject<TestResponse>(json);
public class TestResponse
{
public string[] result { get; set; }
}
and
public class TestResponse
{
public object[] result { get; set; }
}
and
public class TestResponse
{
public string result { get; set; }
}
These were done just to get it to parse.

Open Visual Studio
Open Edit => Click Paste Special => Click Paste Json as Classes
Here is the result:
public class Rootobject
{
public object[] error { get; set; }
public Result result { get; set; }
}
public class Result
{
public XXRPXXBT XXRPXXBT { get; set; }
}
public class XXRPXXBT
{
public string[] a { get; set; }
public string[] b { get; set; }
public string[] c { get; set; }
public string[] v { get; set; }
public string[] p { get; set; }
public int[] t { get; set; }
public string[] l { get; set; }
public string[] h { get; set; }
public string o { get; set; }
}

Related

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

Accessing deeply nested JSON objects in c# using NewtonSoft Deserialization

I am having a very difficult time reaching some deeply nested objects in my JSON
I have a directory with roughly 500 JSON files that I need to read through, and output certain data from so I load the files like this:
public static void getJsonFiles()
{
int i = 0;
string directory = #"Z:\My_JSON_FILES\DataFilesForAnalysis\DataFilesAsJSON";
string[] jsonPath = Directory.GetFiles(directory, "*.json");
foreach(string item in jsonPath)
{
jsonReader(item, i);
i++;
}
}
Once I have the file loaded, I am reading it through File.ReadAllText so I am doing this:
public static void jsonReader(string item, int i)
{
string readJson = File.ReadAllText(item);
RootObject rootObj = JsonConvert.DeserializeObject<RootObject>(readJson);
var resReport = rootObj.ResultsReport;
...
I have created objects of all of the JSON using json2csharp, but when I try to access the deeply nested objects using dot notation (rootObj.ResultsReport.FinalReport.VariantProperties.VariantProperty.VariantName), I get an error 'Object does not contain a definition for FinalReport and no extension method FinalReport...'
My object definition looks like this:
public class VariantProperty
{
public string geneName { get; set; }
public string isVUS { get; set; }
public string variantName { get; set; }
}
public class VariantProperties
{
public string[] VariantProperty { get; set; }
}
public class FinalReport
{
public Object Application { get; set; }
public string ReportId { get; set; }
public string SampleName { get; set; }
public string Version { get; set; }
public Object Sample { get; set; }
public string PertinentNegatives { get; set; }
public Object Summaries { get; set; }
public Object VariantProperties { get; set; }
public Object Genes { get; set; }
public Object Trials { get; set; }
public Object References { get; set; }
public Object Signatures { get; set; }
public Object AAC { get; set; }
}
public class ResultsReport
{
public Object FinalReport { get; set; }
public Object VariantReport { get; set; }
}
public class RootObject
{
public Object ResultsReport { get; set; }
}
The JSON looks like this:
"ResultsReport": {
"CustomerInformation": null,
"FinalReport": {
"#xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"#StagingId": "XXXXXXXX",
"#clinicalId": "XXXXXXXX",
"Application": {
"ApplicationSettings": {
"ApplicationSetting": {
"Name": "Statement",
"Value": "XXXXXXXX"
}
}
},
"ReportId": "XXXXXXXX",
"SampleName": "XXXXXXXX",
"Version": "1",
"Sample": {
"FM_Id": "XXXXXXXX",
"SampleId": "XXXXXXXX",
"BlockId": "XXXXXXXX",
"TRFNumber": "XXXXXXXX",
"TestType": "XXXXXXXX",
"SpecFormat": "XXXXXXXX",
"ReceivedDate": "XXXXXXXX"
},
"PertinentNegatives": null,
"Summaries": {
"#alterationCount": "XXXXXXXX",
"#clinicalTrialCount": "XXXXXXXX",
"#resistiveCount": "XXXXXXXX",
"#sensitizingCount": "XXXXXXXX"
},
"VariantProperties": {
"VariantProperty": [
{
"#geneName": "BARD1",
"#isVUS": "true",
"#variantName": "P358_S364del"
},
{
"#geneName": "GATA2",
"#isVUS": "true",
"#variantName": "P161A"
},
{
"#geneName": "LRP1B",
"#isVUS": "true",
"#variantName": "V4109I"
},
{
"#geneName": "MLL2",
"#isVUS": "true",
"#variantName": "P1191L"
},
{
"#geneName": "NTRK1",
"#isVUS": "true",
"#variantName": "G18E"
},
{
"#geneName": "NUP98",
"#isVUS": "true",
"#variantName": "A447T"
},
{
"#geneName": "TET2",
"#isVUS": "true",
"#variantName": "D1121Y"
},
{
"#geneName": "WT1",
"#isVUS": "true",
"#variantName": "T377_G397>S"
}
]
}
What am I doing wrong? I've followed so many different examples but it just wont seem to work
Write properties like
public ResultsReport ResultsReport { get; set; }
public FinalReport FinalReport { get; set; }
You are using object as property type, thats wrong, it is not about JSON deserialization.
As Volkan said the issue isn't the JSON deserialization. I got your json working by structuring my classes like so:
public class VariantProperty
{
public string geneName { get; set; }
public string isVUS { get; set; }
public string variantName { get; set; }
}
public class VariantProperties
{
public List<VariantProperty> VariantProperty { get; set; }
}
public class FinalReport
{
public Object Application { get; set; }
public string ReportId { get; set; }
public string SampleName { get; set; }
public string Version { get; set; }
public Object Sample { get; set; }
public string PertinentNegatives { get; set; }
public Object Summaries { get; set; }
public VariantProperties VariantProperties { get; set; }
public Object Genes { get; set; }
public Object Trials { get; set; }
public Object References { get; set; }
public Object Signatures { get; set; }
public Object AAC { get; set; }
}
public class ResultsReport
{
public FinalReport FinalReport { get; set; }
}
public class RootObject
{
public ResultsReport ResultsReport { get; set; }
}

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

Creating datamodel from JSON

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.

Approach for parsing json string with different type of objects

I have following json string
{
"serverTime": "2013-08-12 02:45:55,558",
"data": [{
"key1": 1,
"result": {
"sample1": [""],
"sample2": "test2"
}
},{
"key1": 1,
"result": {
"sample3": [""],
"sample4": "test2"
}
}]
}
Using JSONTOC#
Following classes are generated.
public class Result
{
public List<string> sample1 { get; set; }
public string sample2 { get; set; }
public List<string> sample3 { get; set; }
public string sample4 { get; set; }
}
public class Datum
{
public int key1 { get; set; }
public Result result { get; set; }
}
public class RootObject
{
public string serverTime { get; set; }
public List<Datum> data { get; set; }
}
As one can see the tool has generated Result class with all the possible properties.
I am trying to following approach to parse the json
public class Response<T>
{
public Date serverTime;
public ResponseData<T>[] data;
}
public class ResponseDataBase
{
public int key1;
}
public class ResponseData<T> : ResponseDataBase
{
public T result;
}
Here can T be following two classes
Class Result1
{
public List<string> sample1 { get; set; }
public string sample2 { get; set; }
}
Class Result2
{
public List<string> sample3 { get; set; }
public string sample4 { get; set; }
}
I have these class declaration as reference, the class definition can be totally different.
** How can I parse this json by specifying Result type.** I am using JSONFx.net for deserializing back to objects.
Thanks
Classes generated from your JSON data:
public class Result
{
public List<string> sample1 { get; set; }
public string sample2 { get; set; }
}
public class Datum
{
public int key { get; set; }
public Result result { get; set; }
}
public class RootObject
{
public string serverTime { get; set; }
public List<Datum> data { get; set; }
}
User Newtonsoft.Json dll to Deserialize JSON data like:
var obj = JsonConvert.DeserializeObject<RootObject>("yourjsonstring");
then you can use properties of obj like:
var date = DateTime.Parse(obj.serverTime);
and so on.

Categories