public class 2500113075262000 {
public string pair { get; set; }
public string type { get; set; }
public double amount { get; set; }
public int rate { get; set; }
public string timestamp_created { get; set; }
public int status { get; set; }
}
public class Return {
public 2500113075262000 2500113075262000 { get; set; }
}
public class Root {
public int success { get; set; }
public Return #return { get; set; }
}
class 2500113075262000 is constantly changing, this is the order ID, like deserialize
{"success":1,"return":{"2500113075262000":{"pair":"eth_rur","type":"sell","amount":0.00110569,"rate":46100,"timestamp_created":"1608918997","status":0}}}
It looks like it's only the key - presumably the order ID - which is changing. I would suggest removing your Return class entirely, and changing your Root class to have a Dictionary<string, Order>. I'd also suggest writing your classes with idiomatic .NET property names, and using JsonPropertyAttribute to specify the representation in the JSON. So it would be something like this:
public class Order
{
[JsonProperty("pair")]
public string Pair { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
// etc, other properties
}
public class Root
{
[JsonProperty("success")]
public int Success { get; set; }
[JsonProperty("return")]
public Dictionary<string, Order> Returns { get; set; }
}
Related
I have a web service which I get a complex Json object, everything is fine, but there is a class in this object that changes its name in each response according on Item name, this prevents the normal deserialization process
public class Threads
{
public object threads { get; set; }
public object error { get; set; }
public Async async { get; set; }
public Products products { get; set; } => Products Class
}
public class Products
{
//public DR7614060 dr7614060 { get; set; }
// I try to Deserialize the class as Dictionary but nothing happend
Dictionary<string, DR7614060> Pairs { get ; set; }
}
public class DR7614060
{
public string id { get; set; }
public string threadId { get; set; }
public string productId { get; set; }
public bool mainColor { get; set; }
public Productrollup productRollup { get; set; }
}
Json :
https://github.com/Kremed/ContenPageFlowDirection/blob/master/Json.json
I was able to get this configuration to work:
public class Threads
{
[JsonProperty("threads")]
public object ThreadsThreads { get; set; }
[JsonProperty("error")]
public object Error { get; set; }
[JsonProperty("async")]
public ThreadsAsync Async { get; set; }
[JsonProperty("products")]
public Dictionary<string, StupidClassName> Products { get; set; }
}
I think you were on the right track, you just need to move the dictionary up one level to allow for the key value pair to be based on the name of the class. So that leaves the DR7614060 definition. Just give it a proper class name to use for deserialization. Now your Products dictionary will have key = 'given class name' value = 'deserialized object with defined class name'
public partial class StupidClassName // instead of DMxxxxxx
{
[JsonProperty("id")]
public Guid Id { get; set; }
[JsonProperty("threadId")]
public Guid ThreadId { get; set; }
[JsonProperty("productId")]
[JsonConverter(typeof(ParseStringConverter))]
public long ProductId { get; set; }
[JsonProperty("mainColor")]
public bool MainColor { get; set; }
[JsonProperty("productRollup")]
public ProductRollup ProductRollup { get; set; }
// .... more props etc.
}
From the Json you posted I got:
I currently have JSON coming in as follows:
{"36879":[{"min_qty":1,"discount_type":"%","csp_price":10}],"57950":[{"min_qty":1,"discount_type":"flat","csp_price":650}]}
This contains a list of the following records
ProductId
MinQty
DiscountType
Price
I need to deserialize this into the following model:
public class CustomerSpecificPricing
{
string productId { get; set; }
public virtual List<CustomerSpecificPricingDetail> CustomerSpecificPricingDetails { get; set; }
}
public class CustomerSpecificPricingDetail
{
public string min_qty { get; set; }
public string discount_type { get; set; }
public string csp_price { get; set; }
}
The problem is that the "productId" of each record is missing the key name.
If I run my JSON through J2C, I get the following:
public class 36879 {
public int min_qty { get; set; }
public string discount_type { get; set; }
public int csp_price { get; set; }
}
public class 57950 {
public int min_qty { get; set; }
public string discount_type { get; set; }
public int csp_price { get; set; }
}
public class Root {
public List<_36879> _36879 { get; set; }
public List<_57950> _57950 { get; set; }
}
Which is obviously incorrect.
How would I deserialize my object correctly?
You would need to deserialize it into a dictionary first and then map it into the format you require after. Something like this should work:
var dict = JsonConvert.DeserializeObject<Dictionary<string, IEnumerable<CustomerSpecificPricingDetail>>>();
var result = dict.Select(kvp => new CustomerSpecificPricing { ProductId = Int32.Parse(kvp.Key), CustomerSpecificPricingDetails = kvp.Value });
Id also recommend you follow the conventional standards of naming. In this case properties in classes should be PascalCase,
e.g. your classes now become:
public class CustomerSpecificPricing
{
[JsonProperty("productId ")]
public string ProductId { get; set; }
public virtual List<CustomerSpecificPricingDetail> CustomerSpecificPricingDetails { get; set; }
}
and
public class CustomerSpecificPricingDetail
{
[JsonProperty("min_qty")]
public string MinQty { get; set; }
[JsonProperty("discount_type ")]
public string DiscountType { get; set; }
[JsonProperty("csp_price ")]
public string CspPrice { get; set; }
}
I get a JSON response like this :
{
"xpubaddressONE":{"final_balance":123,"n_tx":0,"total_received":0},
"xpubaddressTWO":{"final_balance":25221,"n_tx":0,"total_received":0},
"xpubaddressTHREE":{"final_balance":1123,"n_tx":0,"total_received":0}
}
I want to deserialize it into C# object. I need to build classes like this :
public class xpubaddressONE
{
public int final_balance { get; set; }
public int n_tx { get; set; }
public int total_received { get; set; }
}
public class xpubaddressTHREE
{
public int final_balance { get; set; }
public int n_tx { get; set; }
public int total_received { get; set; }
}
public class xpubaddressTWO
{
public int final_balance { get; set; }
public int n_tx { get; set; }
public int total_received { get; set; }
}
public class RootObject
{
public xpubaddressONE one { get; set; }
public xpubaddressTWO two { get; set; }
public xpubaddressTHREE three { get; set; }
}
My goal is to remove additional classes(xpubaddressONE,xpubaddressTWO,xpubaddressTHREE) and access objects like this :
RootObject.final_balance
I would try deserializing a Dictionary<string, xpubaddress>, where xpubaddress is:
public class xpubaddress
{
public int final_balance { get; set; }
public int n_tx { get; set; }
public int total_received { get; set; }
}
This should then give you a dictionary with 3 keys that you can inspect with foreach, TryGetValue, etc.
Alternatively, stick with your root type, but share the inner type:
public class xpubaddress
{
public int final_balance { get; set; }
public int n_tx { get; set; }
public int total_received { get; set; }
}
public class RootObject
{
public xpubaddress xpubaddressONE{ get; set; }
public xpubaddress xpubaddressTWO{ get; set; }
public xpubaddress xpubaddressTHREE { get; set; }
}
You may also find it easier to leave the property names as idiomatic .NET names, and use [JsonProperty] or [DataMember] to rename them, i.e.
[JsonProperty("final_balance")]
public int FinalBalance { get; set; }
You can introduce the single xpubaddress class, like
public class xpubaddress
{
public int final_balance { get; set; }
public int n_tx { get; set; }
public int total_received { get; set; }
}
and then deserialize it into IDictionary<string, xpubaddress> for example, add access objects using the xpubaddressONE, xpubaddressTWO, etc., keys
var result = JsonConvert.DeserializeObject<IDictionary<string, xpubaddress>>(json);
var balance = result?["xpubaddressONE"]?.final_balance ?? 0;
I have a C# classes and I need to parse JSON into it.
The class has a List<> from another class.
The class structure is like this.
public class OrderFund {
public int OrderID { get; set; }
public int BrokerID { get; set; }
public string SettlementMethod { get; set; }
public List<SettlementSap> SettlementsSap { get; set; }
}
public class SettlementSap {
public string SapMonetaryAccountNo { get; set; }
public string SapMonetaryAccountType { get; set; }
public string SapMonetaryAccountOffice { get; set; }
}
My JSON is like this.
{
"settlementMethod": "SAP",
"BrokerID": 1,
"OrderID": 1,
"Settlements": [
{
"SapMonetaryAccountNo": "400245892464",
"SapMonetaryAccountType": "CA",
"SapMonetaryAccountOffice": "AR"
}
]
}
I load my JSON file like this...
static OrderFund LoadJson(string file) {
string dire = Directory.GetCurrentDirectory();
using (StreamReader r = new StreamReader(dire + "\\" + file)) {
string json = r.ReadToEnd();
OrderFund items = JsonConvert.DeserializeObject<OrderFund>(json);
return items;
}
}
The data load fine into OrderFun Class but OrderFund.SettlementsSap is null.
How can I load Settlements into SettlementsSap?
That's because you have named the field SettlementsSap but your Json field is called Settlements...
You could rename the field in your class;
public class OrderFund
{
public int OrderID { get; set; }
public int BrokerID { get; set; }
public string SettlementMethod { get; set; }
public List<SettlementSap> Settlements { get; set; }
}
or add a [JsonProperty("Settlements")]
attribute to the field like so;
public class OrderFund
{
public int OrderID { get; set; }
public int BrokerID { get; set; }
public string SettlementMethod { get; set; }
[JsonProperty("Settlements")]
public List<SettlementSap> SettlementsSap { get; set; }
}
You just use a function of Visual Studio which convert your json into a model class
Goto: Edit -> Paste special -> Paste JSON as Class
The model class created by this feature will solve your problem
So, visiblely, you must rename SettlementsSap by Settlements
public class OrderFund
{
public string settlementMethod { get; set; }
public int BrokerID { get; set; }
public int OrderID { get; set; }
public Settlement[] Settlements { get; set; }
}
public class Settlement
{
public string SapMonetaryAccountNo { get; set; }
public string SapMonetaryAccountType { get; set; }
public string SapMonetaryAccountOffice { get; set; }
}
The problem is with the naming. In the JSON, the name is Settlements. But in the class definition of OrderFund it is named as SettlementsSap
I'm trying to work with AWS SDK in C# to follow and update a price catalog.
I'm using the method GetProductsAsync to list EC2 products for example, I then try to deserialize the response.
I use Json.Net to deserialize my response into a class I created using the "Paste JSON as classes" function from Visual Studio.
The object is somewhat populated, but the pricing model follows a weird JSON pattern.
Here is an extract of the object:
"terms":{
"OnDemand":{
"FBKCX9C4KX8NSVN3.JRTCKXETXF":{
"priceDimensions":{
"FBKCX9C4KX8NSVN3.JRTCKXETXF.6YS6EN2CT7":{
"unit":"Hrs",
"endRange":"Inf",
"description":"$2.47 per On Demand RHEL m4.10xlarge Instance Hour",
"appliesTo":[
],
"rateCode":"FBKCX9C4KX8NSVN3.JRTCKXETXF.6YS6EN2CT7",
"beginRange":"0",
"pricePerUnit":{
"USD":"2.4700000000"
}
}
},
The IDs under OnDemand and PriceDimensions seem to be references to other objects; therefore, they are not populated when I deserialize the JSON object, as they are different per product type.
Has anyone succeeded in getting pricing information for AWS assets?
For JSON objects having keys which can vary, you can use a Dictionary<string, T> in place of a regular class, where T is a class representing the item data. So in your case, you'd need a dictionary for both OnDemand and priceDimensions. The resulting class definitions would look like this:
public class OuterObject
{
public Terms terms { get; set; }
}
public class Terms
{
public Dictionary<string, OnDemandItem> OnDemand { get; set; }
}
public class OnDemandItem
{
public Dictionary<string, PriceDimensionsItem> priceDimensions { get; set; }
}
public class PriceDimensionsItem
{
public string unit { get; set; }
public string endRange { get; set; }
public string description { get; set; }
public object[] appliesTo { get; set; }
public string rateCode { get; set; }
public string beginRange { get; set; }
public PricePerUnit pricePerUnit { get; set; }
}
public class PricePerUnit
{
public string USD { get; set; }
}
Demo: https://dotnetfiddle.net/dJ5jmQ
Note: you could also use a Dictionary<string, string> in place of the PricePerUnit class if you will be dealing with a lot of different currencies. If there will just one or two, then having a strongly-typed class with properties for each possible currency will work fine. For example, you could add a property public string EUR { get; set; } to handle Euro.
AWS SDK have one more "level" after OnDemand.
I made my own class based on Brian Rogers answer, and i add the rest of the class to support Reserved and Products, making a nested class.
public class OuterObject
{
public Dictionary<string, Products> products { get; set; }
public Terms terms { get; set; }
}
public class Products
{
public string sku { get; set; }
public string productFamily { get; set; }
public Attributes attributes { get; set; }
}
public class Attributes
{
public string servicecode { get; set; }
public string location { get; set; }
public string locationType { get; set; }
public string instanceType { get; set; }
public string currentGeneration { get; set; }
public string vcpu { get; set; }
public string memory { get; set; }
public string operatingSystem { get; set; }
public string licenseModel { get; set; }
public string preInstalledSw { get; set; }
public string tenancy { get; set; }
}
public class Terms
{
public Dictionary<string, Dictionary<string, OnDemandItem>> OnDemand { get; set; }
public Dictionary<string, Dictionary<string, OnDemandItem>> Reserved { get; set; }
}
public class OnDemandItem
{
public string offerTermCode { get; set; }
public string sku { get; set; }
public Dictionary<string, PriceDimensionsItem> priceDimensions { get; set; }
public TermAttributes termAttributes { get; set; }
}
public class PriceDimensionsItem
{
public string unit { get; set; }
public string endRange { get; set; }
public string description { get; set; }
public object[] appliesTo { get; set; }
public string rateCode { get; set; }
public string beginRange { get; set; }
public PricePerUnit pricePerUnit { get; set; }
}
public class PricePerUnit
{
public string USD { get; set; }
}
public class TermAttributes
{
public string LeaseContractLength { get; set; }
public string OfferingClass { get; set; }
public string PurchaseOption { get; set; }
}