i need to POST arrays within object to api that will looks like this:
{
"ds_seatInfo": [
{
"SEAT_LOC_NO": "00201901",
"SEAT_LOC_NO": "00201902"
}
],
"SCN_SCH_SEQ": "13178",
"REQ_FG_CD": "01",
"LOCK_APRV_KEY": "123123"
}
i was tried using Models that define as follow:
public class ds_seatInfo
{
public List<string> SEAT_LOC_NO { get; set; }
}
public class BookParam
{
public string SCN_SCH_SEQ { get; set; }
public ds_seatInfo ds_seatInfo { get; set; }
public string REQ_FG_CD { get; set; }
public string LOCK_APRV_KEY { get; set; }
}
but the result aren't as expected, that's model return:
"{\"SCN_SCH_SEQ\":\"13178\",\"ds_seatInfo\":{\"SEAT_LOC_NO\":[\"00201901\",\"00201902\"]},\"REQ_FG_CD\":\"01\",\"LOCK_APRV_KEY\":\"123123\"}"
which means the SEAT_LOC_NO doesn't read as expected. i am using Newtonsoft for Serialize the Model.
What should i do?
Haven't tested it, but may be this will help you or get you in the right direction:
public class BookParam
{
[JsonProperty("ds_seatInfo")]
public List<KeyValuePair<string, string>> SetInfos = new List<KeyValuePair<string, string>>();
[JsonProperty("SCN_SCH_SEQ")]
public string ScnSchSeq { get; set; }
[JsonProperty("REQ_FG_CD")]
public string ReqFgCd { get; set; }
[JsonProperty("LOCK_APRV_KEY")]
public string LockAprvKey { get; set; }
}
And when you add items to SetInfos try like this:
SetInfos.Add(new KeyValuePair<string, string>("SEAT_LOC_NO", "00201901"));
Edit
Another possible implementation
public class BookParam
{
[JsonProperty("ds_seatInfo")]
public List<SeatInfo> DsSeatInfo = new List<SeatInfo>();
[JsonProperty("SCN_SCH_SEQ")]
public string ScnSchSeq { get; set; }
[JsonProperty("REQ_FG_CD")]
public string ReqFgCd { get; set; }
[JsonProperty("LOCK_APRV_KEY")]
public string LockAprvKey { get; set; }
}
public class SeatInfo()
{
[JsonProperty("SEAT_LOC_NO")]
public string SeatLocNo { get; set; }
}
Related
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'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; }
}
I have tried countless methods to Parse my JSON string (Steam Public Data), yet nothing seems to work. I just want to be able to extract values from the string. For Example, obtaining the value of personaname which would return SlothGod. I have JSON.NET installed in my project.
Here is my JSON:
{
"response": {
"players": [
{
"steamid": "76561198301407459",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "SlothGod",
"lastlogoff": 1508389707,
"commentpermission": 1,
"profileurl": "http://steamcommunity.com/id/sleuthgud/",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba.jpg",
"avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba_medium.jpg",
"avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/09/09cea52b91136fb3306c57771a746db2823b91ba_full.jpg",
"personastate": 0,
"realname": "Josh",
"primaryclanid": "103582791460168790",
"timecreated": 1462086929,
"personastateflags": 0,
"loccountrycode": "AU",
"locstatecode": "QLD"
}
]
}
}
Main method suggested to me:
public class Details
{
public string personaname { get; set; }
}
private void GetSteamDetails()
{
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Details>(SteamDetailsJson);
SteamName = data.personaname;
}
This is placed before Page_Load(). I then call GetSteamDetails(); when I want to fetch the name.
After my question being down voted, I decided to not give up on this problem. After extensive research, trial and error, and YouTube tutorials which are the most helpful IMO. I found that the data was containing a JSON array, and yes I will admit, I was confused with this, but the answer was to simply treat it like a C# array and add [1] to the end of players.
Details details = new Details();
public class Details
{
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public string realname { get; set; }
public string personaname { get; set; }
public string steamid { get; set; }
}
private void GetSteamDetails()
{
var SteamDetails= JsonConvert.DeserializeObject<dynamic>(SteamDetailsJson);
avatar = SteamDetails.response.players[1].avatar.ToString();
personaname = SteamDetails.response.players[1].personaname.ToString();
}
Based on the JSON string you provided, you should have the following C# classes to support it, or to deserialize the JSON object values into: I used this link to generate the classes.
public class Player
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public int lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public int timecreated { get; set; }
public int personastateflags { get; set; }
public string loccountrycode { get; set; }
public string locstatecode { get; set; }
}
public class Response
{
public List<Player> players { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
Then, using Newtonsoft.Json, you can deserialize the JSON object into your C# classes as follow:
JsonConvert.DeserializeObject<RootObject>("yourJsonString");
You mention that Newtonsoft.Json already referenced in the project.
Use class to represent json data structure, then you can easy deserialize it.
You can use only properties you need in the class.
public class Player
{
public string personaname { get; set; }
}
var player = Newtonsoft.Json.JsonConvert.DeserializeObject<Player>(jsonString);
// use player.personaname
For updates question create classes which represent your data structure
public class Team
{
public List<Player> players { get; set; }
}
public class Response
{
public Team response { get; set; }
}
You can use http://json2csharp.com/ to generate a class automatically from a JSON string.
I'm returning data from transportapi.com & loading it into an object, but the data within the json array isn't being included.
The json returned is:
{
"atcocode": "490012745J",
"smscode": "47889",
"request_time": "2016-11-11T22:10:42+00:00",
"departures": {
"55": [
{
"mode": "bus",
"line": "55",
"line_name": "55",
"direction": "Bakers Arms",
"operator": "TFL",
"date": null,
"expected_departure_date": "2016-11-11",
"aimed_departure_time": null,
"expected_departure_time": "22:19",
"best_departure_estimate": "22:19",
"source": "Countdown instant"
}
]
}
}
Controller code:
var source = "http://transportapi.com/v3/uk/bus/stop/490012745J/live.json?api_key=[key]&app_id=[appid]";
Uri sourceUri = new Uri(source);
System.Net.Http.HttpClient sourceClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage sourceResponse = await sourceClient.GetAsync(sourceUri);
var sourceArray = await sourceResponse.Content.ReadAsStringAsync();
var selections = JsonConvert.DeserializeObject<RootObject>(sourceArray);
Model class:
public class BusDepartures
{
public string mode { get; set; }
public string line { get; set; }
public string line_name { get; set; }
public string direction { get; set; }
public string busoperator { get; set; }
public object date { get; set; }
public string expected_departure_date { get; set; }
public object aimed_departure_time { get; set; }
public string expected_departure_time { get; set; }
public string best_departure_estimate { get; set; }
public string source { get; set; }
}
public class Departures
{
// First attempt, use BusDepartures object.
//public List<BusDepartures> BusDepartures { get; set; }
// Second attempt (as "55" is an array), use array, then convert to object later.
public string[] routes { get; set; }
}
public class RootObject
{
public string atcocode { get; set; }
public string smscode { get; set; }
public string request_time { get; set; }
public Departures departures { get; set; }
}
Within the Departures class I did try and create a BusDepartures object to store the details of the departures, but I wondered whether, as it is an array, I should use the routes array instead? However when stepping through the code, the BusDepartures object (when it was uncommented) and the routes array were both null.
Any ideas? What am I missing?
Update:
Thanks to botond.botos for the answer. I amended my class to
public class RootObject
{
public string atcocode { get; set; }
public string smscode { get; set; }
public string request_time { get; set; }
public IDictionary<int, IEnumerable<BusDepartures>> departures { get; set; }
}
and it worked.
You won't need the Departures class, and try to change the RootObject class the following way:
public class RootObject
{
public string atcocode { get; set; }
public string smscode { get; set; }
public string request_time { get; set; }
public IDictionary<int, IEnumerable<BusDepartures>> departures { get; set; }
}
I'm pretty sure your trying to map the property name "55" to a non-existent c# property. Either modify the json (which i'm assuming you can't) or use a more generic property to handle the departures.
I'm thinking maybe something like a generic Dictionary(Of int, List(of Departure)) .... which is of course vb and I'm going to guess at new Dictionary<#int, List>() in c# ? :)
public class departures {
public Dictionary<int, List<Departure>> BusDepartures {get; set; }
}
I am New to JSON and API
I am trying to get some data from an API for which I have Json and want to make a class for it.when I convert it using josn2csharp I get following code. Please let me know what sholud be the proper format of my class so that it converts into json.
public class DataSet {
public string __invalid_name__-i:nil { get; set; } }
public class GenericObject {
public string __invalid_name__-xmlns:d2p1 { get; set; }
public string __invalid_name__-i:type { get; set; }
public string __invalid_name__#text { get; set; } }
public class Message {
public string __invalid_name__-i:nil { get; set; } }
public class FunctionResponse {
public string __invalid_name__-xmlns:i { get; set; }
public string __invalid_name__-xmlns { get; set; }
public DataSet DataSet { get; set; }
public GenericObject GenericObject { get; set; }
public Message Message { get; set; }
public string Success { get; set; } }
public class RootObject {
public FunctionResponse FunctionResponse { get; set; } }
use this question as reference in this I came to know how to write for
public string invalid_name#text { get; set; }
but what about others.
please help
edit 1:
{
"DataSet": {
"#nil": "true"
},
"GenericObject": {
"#type": "d2p1:boolean",
"#text": "true"
},
"Message": {
"#nil": "true"
},
"Success": "true"
}
Example:
{
"json":
{
"#thekeyinsidejsonproperty": "value"
}
}
you shoud have
public class RootObject
{
[JsonProperty("json")]
public Json jsonobj;
}
public class Json
{
[JsonProperty("#thekeyinsidejsonproperty")]
public string somepropertyname{ get; set; }
}
hope it helps! :)