{
"transactionId" : XXXXX,
"uri" : "https://XXX.XXXXXXXX.XXXX/XXX/XXX",
"terminalId" : 1,
"action" : "CHARGE",
"amountBase" : "3.00",
"amountTotal" : "3.00",
"status" : "CAPTURE",
"created" : "2015-01-24T07:24:10Z",
"lastModified" : "2015-01-24T07:24:10Z",
"response" :
{
"approved" : true,
"code" : "00",
"message" : "Approved",
"processor" :
{
"authorized" : true,
"approvalCode" : "XXXX",
"avs" :
{
"status" : "NOT_REQUESTED"
},
}
},
"settlement" :
{
"settled" : false
},
"vault" :
{
"type" : "CARD",
"accountType" : "VISA",
"lastFour" : "1111"
}
}
I see this has got a lot of down votes but no one is actually offering any advice. The json above is not a natural fit for a Dictionary but should be de-serialized into an object.
Response, settlement and vault all have their own properties and as such should be their own objects.
Look into Json.net for a good way to convert json into your c# objects. If you are stuck on how you would represent this object in C# then you need to read a good book on programming specifically one that covers Object Orientated programming.
Stack is a great resource for these questions but you need to try and show you have done your own research first otherwise others will just mark your questions down.
Are you receiving a POST that contains a JSON ?
You can use something like this , create an instance of Request class and assign the JSON obj to that instance. You should be able to access the parameters via request instance.
The basic structure will look some thing like this :
public class Request
{
public Int64 transactionId { get; set; }
public string uri { get; set; }
public int terminalId { get; set; }
public string action { get; set; }
public string amountBase { get; set; }
public int amountTotal { get; set; }
public string status { get; set; }
public DateTime created { get; set; }
public DateTime lastModified { get; set; }
public Response response { get; set; }
public Settlement settlement { get; set; }
public Vault vault { get; set; }
}
public class Response
{
public bool approved { get; set; }
public int code { get; set; }
public string message { get; set; }
public Processor processor { get; set; }
}
public class Processor
{
public bool authorized { get; set; }
public string approvedCode { get; set; }
public AVS avs { get; set; }
}
public class AVS
{
public string status { get; set; }
}
public class Settlement
{
public bool settled { get; set; }
}
public class Vault
{
public string type { get; set; }
public string accountType { get; set; }
public string lastFour { get; set; }
}
Hope this helps !!
Related
I don't know if there is an existing name for that case, but I'm trying to retrieve data from NASA API (https://api.nasa.gov/) and I have a simple challenge to catch a list of objects near earth. Here is the JSON response I have from the GET request I do to "https://api.nasa.gov/neo/rest/v1/feed?...."
{
"links": {
"next": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-04&end_date=2021-07-04&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym",
"prev": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-02&end_date=2021-07-02&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym",
"self": "http://www.neowsapp.com/rest/v1/feed?start_date=2021-07-03&end_date=2021-07-03&detailed=false&api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym"
},
"element_count": 6,
"near_earth_objects": {
"2021-07-03": [
{
"links": {
"self": "http://www.neowsapp.com/rest/v1/neo/3701710?api_key=NjgpxgSbYHXyFSBI3HaOhRowtjMZgAKv2t4DMRym"
},
"id": "3701710",
"neo_reference_id": "3701710",
"name": "(2014 WF497)",
"nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=3701710",
"absolute_magnitude_h": 20.23,
"estimated_diameter": {
"kilometers": {
}
And that's the way it is built in Visual Studio (using the Special Paste option for JSON)
public class NearEarthObject
{
public Links links { get; set; }
public int element_count { get; set; }
public Near_Earth_Objects near_earth_objects { get; set; }
}
public class Links
{
public string next { get; set; }
public string prev { get; set; }
public string self { get; set; }
}
public class Near_Earth_Objects
{
public _20210703[] _20210703 { get; set; }
}
public class _20210703
{
public Links1 links { get; set; }
public string id { get; set; }
public string neo_reference_id { get; set; }
public string name { get; set; }
public string nasa_jpl_url { get; set; }
public float absolute_magnitude_h { get; set; }
public Estimated_Diameter estimated_diameter { get; set; }
public bool is_potentially_hazardous_asteroid { get; set; }
public Close_Approach_Data[] close_approach_data { get; set; }
public bool is_sentry_object { get; set; }
}
The question is, inside of the element "near_earth_objects", there is an element called "2021-07-03" (the date of the data I requested), the problem is that I am trying to include it into a DataGridView made in .NET C# (Windows Forms, but that doesn't matters here, I think) and the user wants to get the information by date. So, "2021-07-03" is a valid member just for one day, and the user should be able to get data from multiple days.
So, is there a way in C# to get all child objects inside of near_earth_objects without knowing their names since there will be the option to search for asteroids from date X to Y in my application?
Using System.Text.Json
The API response will map to the following classes
public class Neo
{
public Links Links { get; set; }
public int ElementCount { get; set; }
public Dictionary<string, List<NearEarthObject>> NearEarthObjects { get; set; }
}
public class Links
{
public string Next { get; set; }
public string Prev { get; set; }
public string Self { get; set; }
}
public class NearEarthObject
{
public Links Links { get; set; }
public string Id { get; set; }
public string Name { get; set; }
// Other properties
}
The NearEarthObjects is simply a Dictionary, where the key is the formatted date and value is a List containing NearEarthObject
The PropertyNamingPolicy will allow us to support the API's underscore property naming convention.
public class UnderscoreNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
return name.Underscore();
}
}
Example usage
// using using System.Text.Json;
var response = await new HttpClient().GetStringAsync(url);
var neo = JsonSerializer.Deserialize<Neo>(response, new JsonSerializerOptions
{
PropertyNamingPolicy = new UnderscoreNamingPolicy()
});
foreach(var neos in neo.NearEarthObjects)
{
Console.WriteLine(neos.Key);
}
use System.Text.Json, JsonNamingPolicy
demo code
public class DynamicNamePolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
var today = DateTime.Today.ToString("yyyy-MM-dd");
if (name.Equals("DateData")) //model property name
return today; //convert to json string property name
return name;
}
}
//data deserialize
string data = ""; //json string
var obj = JsonSerializer.Deserialize<NearEarthObject>(data, new JsonSerializerOptions
{
PropertyNamingPolicy = new DynamicNamePolicy(),
});
I have a json file, where i have to validate a json attribute element value based on another json element attribute value. But if there json elements with the same name. It always takes the last value always instead of parsing the json data fully. Please guide me.
Below the sample json file
{
"PLMXML":{
"language":"en-us",
"author":"Developer",
"date":"2020-05-22",
"traverseRootRefs":"#id6",
"Operation":{
"id":"id21",
"subType":"BS4_BaOP",
"catalogueId":"70700000209604"
},
"Operation":{
"id":"id28",
"subType":"BS4_BaOP",
"catalogueId":"70700000209603"
},
"OperationRevision":{
"id":"id6",
"subType":"BS4_BaOPRevision",
"masterRef":"#id21",
"revision":"A1"
}
}
}
And below the code which im trying to use
public void Readjsonfile(string jsondata)
{
var message = JsonConvert.DeserializeObject<plmxmldatamodel>(jsondata);
if (String.Equals(message.PLMXML.traverseRootRefs.Substring(1), message.PLMXML.OperationRevision.id))
{
Console.WriteLine("Condtion1");
if (String.Equals(message.PLMXML.OperationRevision.masterRef.Substring(1), message.PLMXML.Operation.id))
{
Console.WriteLine("Condition_2");
//Do something based on the condtion
}
}
}
public class Operation
{
public string id { get; set; }
public string subType { get; set; }
public string catalogueId { get; set; }
}
public class OperationRevision
{
public string id { get; set; }
public string subType { get; set; }
public string masterRef { get; set; }
}
public class PLMXML
{
public string language { get; set; }
public string author { get; set; }
public string date { get; set; }
public string traverseRootRefs { get; set; }
public Operation Operation { get; set; }
public OperationRevision OperationRevision { get; set; }
}
public class plmxmldatamodel
{
public PLMXML PLMXML { get; set; }
}
When i try to dedug this in the second if condtion, the value for message.PLMXML.Operation.id is always id28 , because of which second if condition fails. While the first if condition is passed as there is only one message.PLMXML.OperationRevision.id. i wanted behaviour where it would check complete json data and check if message.PLMXML.Operation.id with value id21 is present or not , So my data gets passed. Please kindly guide me here.I am very new to C# here.
From my observation you have couple of issues.
What happen you have double keys, and your parser taking the last value not the first one.
First of all your json should be corrected. I assume you have access to change your json and operation should be an array like follow:
{
"PLMXML":{
"language":"en-us",
"author":"Developer",
"date":"2020-05-22",
"traverseRootRefs":"#id6",
"Operations":[
{
"id":"id21",
"subType":"BS4_BaOP",
"catalogueId":"70700000209604"
},
{
"id":"id28",
"subType":"BS4_BaOP",
"catalogueId":"70700000209603"
}
],
"OperationRevision":{
"id":"id6",
"subType":"BS4_BaOPRevision",
"masterRef":"#id21",
"revision":"A1"
}
}
}
When array in place than use an online tool like to validate your json and use this tool to create a model.
Your model will be like this:
public partial class PlmxmlDataModel
{
[JsonProperty("PLMXML")]
public Plmxml Plmxml { get; set; }
}
public partial class Plmxml
{
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("author")]
public string Author { get; set; }
[JsonProperty("date")]
public DateTimeOffset Date { get; set; }
[JsonProperty("traverseRootRefs")]
public string TraverseRootRefs { get; set; }
[JsonProperty("Operations")]
public Operation[] Operations { get; set; }
[JsonProperty("OperationRevision")]
public OperationRevision OperationRevision { get; set; }
}
public partial class OperationRevision
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("subType")]
public string SubType { get; set; }
[JsonProperty("masterRef")]
public string MasterRef { get; set; }
[JsonProperty("revision")]
public string Revision { get; set; }
}
public partial class Operation
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("subType")]
public string SubType { get; set; }
[JsonProperty("catalogueId")]
public string CatalogueId { get; set; }
}
And your method like this:
public void Readjsonfile(string jsondata)
{
var message = JsonConvert.DeserializeObject<PlmxmlDataModel>(jsondata);
if (String.Equals(message.Plmxml.TraverseRootRefs.Substring(1), message.Plmxml.OperationRevision.Id))
{
Console.WriteLine("Condtion1");
if (String.Equals(message.Plmxml.OperationRevision.MasterRef.Substring(1), message.Plmxml.Operations[0].Id))
{
Console.WriteLine("Condition_2");
//Do something based on the condtion
}
}
}
Now in your method I am looking for array index 0 with contain id 28, but if you are look for id 28 in any of the array then you can do some thing like:
if (message.Plmxml.Operations.Any(e => e.Id == message.Plmxml.OperationRevision.MasterRef.Substring(1)))
I have a task to fetch the list of all missing updates using a C# .NET Framwork 4.7.2 windows Service which runs at specific intervals.
I have gotten this far to Fetch the Missing updates following this Answer.
Now I need to Put all the Fetched data in a JSON file using the following Format:
{
"hostName": "LRD-SomeHost",
"ip" : "192.168.13.12",
"mac" : "MAC:23:23:123:AS"
"timeStamp" : "CURRENT_TIME_STAMP",
"updates" : [
{
"updateID": "b32e464f-2e4a-4109-9018-33583a079a8a",
"updateDetails": [
{
"patchDescription" : "Some Long Description",
"patchCategory" : "28bc880e-0592-4cbf-8f95-c79b17911d5f"
"patchType" : "UpdateClassification"
"patchName" : "Update Rollups"
},
{
"patchDescription" : "Windows 10"
"patchCategory" : "a3c2375d-0c8a-42f9-bce0-28333e198407"
"patchType" : "Product"
"patchName" : "Windows 10"
},
{
"patchDescription" : "Windows 10 LTSB"
"patchCategory" : "d2085b71-5f1f-43a9-880d-ed159016d5c6"
"patchType" : "Product"
"patchName" : "Windows 10 LTSB"
}
]
}
]
}
Following is my C# Model:
namespace UpdateCollector
{
public class Host
{
public string hostname { get; set; }
public string ip { get; set; }
public string mac { get; set; }
public DateTime? timeStamp { get; set; }
public List<Updates> updates { get; set; }
}
public class Updates
{
public string updateID { get; set; }
public List<UpdateDetails> updateDetails { get; set; }
}
public class UpdateDetails
{
public string patchDescription { get; set; }
public string patchCategory { get; set; }
public string patchType { get; set; }
public string patchName { get; set; }
}
}
My Question is How to put my C# Data in this Format?
Thanks
You could use Json.NET to achieve this, here is a possible implementation:
First you need to install the package using NuGet:
Install-Package Newtonsoft.Json -Version 12.0.3
Then you define your classes in the same way you are doing, you can, however, use C# naming conventions and make use of attributes to specify different names for serialization:
public class Host
{
[JsonProperty(PropertyName = "hostname")]
public string Hostname { get; set; }
[JsonProperty(PropertyName = "ip")]
public string Ip { get; set; }
[JsonProperty(PropertyName = "mac")]
public string Mac { get; set; }
[JsonProperty(PropertyName = "timeStamp")]
public DateTime? TimeStamp { get; set; }
[JsonProperty(PropertyName = "updates")]
public List<Updates> Updates { get; set; }
}
public class Updates
{
[JsonProperty(PropertyName = "updateID")]
public string UpdateId { get; set; }
[JsonProperty(PropertyName = "updateDetails")]
public List<UpdateDetails> UpdateDetails { get; set; }
}
public class UpdateDetails
{
[JsonProperty(PropertyName = "patchDescription")]
public string PatchDescription { get; set; }
[JsonProperty(PropertyName = "patchCategory")]
public string PatchCategory { get; set; }
[JsonProperty(PropertyName = "patchType")]
public string PatchType { get; set; }
[JsonProperty(PropertyName = "patchName")]
public string PatchName { get; set; }
}
To serialize your class to json you can use the following statement:
var host = new Host();
// Fill all the properties, lists etc...
string json = JsonConvert.SerializeObject(host, Formatting.Indented);
To deserialize a json string back to the a C# object you use the opposite statement:
Host host = JsonConvert.DeserializeObject<Host>(json);
The code above should work for most cases but if you need to serialize / deserialize any of your objects in a special way you can write a custom JsonConverter: see here for an example.
Install Newtonsoft.Json package and do serialization of your object.
follow below code example.
List<Host> dataList=new List<Host>();
string jsonString = JsonConvert.SerializeObject(dataList);
I have been trying to get this json to deserialize for two days now using RestSharp. I have gone through the RestSharp github site, looked at countless examples, and spent much time here on Stack Overflow to try and find the answer to no avail. My code had previously worked perfectly but the vendor changed their API version and I was forced to do an update to keep using the application for my legal practice. My json is as follows(client info has been removed and replaced with generic info):
{
"data":[
{
"id":1035117666,
"client":
{
"id":905422394,
"name":"client1"
},
"display_number":"11-00012",
"description":"General",
"practice_area":
{
"id":4269978,
"name":"Business"
},
"status":"Open",
"open_date":"2011-12-14",
"close_date":null,
"billing_method":"hourly"
},
{
"id":1035117768,
"client":
{
"id":905422506,
"name":"client2"
},
"display_number":"12-00037",
"description":"HOA",
"practice_area":
{
"id":4269978,
"name":"Business"
},
"status":"Open",
"open_date":"2012-08-07",
"close_date":null,
"billing_method":"hourly"
}
],
"meta":
{
"paging":
{
"next":"https://app.goclio.com/api/v4/matters.json?fields=id%2C+client%7Bid%2C+name%7D%2C+display_number%2C+description%2C+practice_area%7Bid%2C+name%7D%2C+status%2C+open_date%2C+close_date%2C+billing_method&limit=2&page_token=BAh7BjoLb2Zmc2V0aQc%3D--b1ea3eba20c8acefbcdfc7868debd1e0ee630c64&status=Open"
},
"records":91
}
}
I built the following schema within my c# code:
public class MatterList
{
public List<Matter> matters { get; set; }
public Meta meta { get; set; }
}
public class Meta
{
public Paging paging { get; set; }
public int records { get; set; }
}
public class Paging
{
public string previous { get; set; }
public string next { get; set; }
}
[DeserializeAs(Name = "data")]
public class Matter
{
public int id { get; set; }
public Client client { get; set; }
public string display_number { get; set; }
public string description { get; set; }
public PracticeArea practice_area { get; set; }
public string status { get; set; }
public DateTime open_date { get; set; }
public DateTime close_date { get; set; }
public string billing_method { get; set; }
public string type = "matter";
}
public class PracticeArea
{
public int id { get; set; }
public string name { get; set; }
}
public class Client
{
public int id { get; set; }
public string name { get; set; }
}
When I run the RestSharp deserialize method I am sending the result to an object of type MatterList using the following line of code
MatterList matterList = jsonHandler.Deserialize<MatterList>(response);
I have so far attempted to deserialize without the Meta or Paging POCO classes with the accompanying change to the MatterList class (taking out the Meta property).
I have tried with and without the [DeserializeAs(Name="data")] directive.
I have tried to set the RootElement of the json response prior to deserialization.
I have tried to shorthand the deserialization by combining it with the Execute request code
IRestResponse<MatterList> matterList = client.Execute<MatterList>(request);
I have created a container class called MatterContainer which I placed between MatterList and Matter classes in the schema:
public class MatterList
{
public List<MatterContainer> matters { get; set; }
}
public class MatterContainer
{
public Matter matter { get; set; }
}
public class Matter
{
public int id { get; set; }
public Client client { get; set; }
public string display_number { get; set; }
public string description { get; set; }
public PracticeArea practice_area { get; set; }
public string status { get; set; }
public DateTime open_date { get; set; }
public DateTime close_date { get; set; }
public string billing_method { get; set; }
public string type = "matter";
}
I know I am getting the json response back from the server correctly so my request is proper and MatterList is not null after deserialization. The problem is that I cannot get the deserialization to actually populate the List matters within the MatterList class.
I have been looking at this off and on for two days and cannot get past this hurdle. If anyone sees what I did wrong I would greatly appreciate the insight, I am at a point where I cannot progress further with my application.
Thanks!
I think your [DeserializeAs(Name = "data")] attribute is in the wrong place. Try putting it in the root class instead:
public class MatterList
{
[DeserializeAs(Name = "data")]
public List<Matter> matters { get; set; }
public Meta meta { get; set; }
}
alternatively, try renameing that property to data
I am receiving the json response of below format from an api. I am trying to deserialze it with custom class.
{
"TraceEvent": {
"Attributes": {
"Commodity": "APPLES",
"Variety": "Green"
},
"Codes": [{
"devicename": "",
"code": "901491877572115",
"timestamp": "2018-02-15T19:33:29.4418926+05:30"
}, {
"devicename": "",
"code": "6657287134488755",
"timestamp": "2018-02-15T19:33:29.4418926+05:30"
}
]
}
}
Below is my custom class used for deserialize
public class EventContainer
{
[JsonProperty("TraceEvent")]
public TraceEvent TraceEvent { get; set; }
}
public class TraceEvent
{
[JsonProperty("attributes")]
public TraceAttributes Attributes { get; set; }
[JsonProperty("codes")]
public TraceCodes Codes { get; set; }
}
public class TraceAttributes
{
[JsonProperty("commodity")]
public string Commodity { get; set; }
[JsonProperty("variety")]
public string Variety { get; set; }
}
public class TraceCodes
{
public TraceCodes()
{
Codes = new List<TraceCode>();
}
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}
public class TraceCode
{
[JsonProperty("devicename")]
public string DeviceName { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("timestamp")]
public DateTime Timestamp { get; set; }
}
In the receiver side, i am getting null for the Codes. Plesae refer my debug screen in api receiver code,
Can any one tell me how to rewrite my custom class to deserialize the Codes list from JSON api
Thanks for the help.
Change the class structure. The Codes should be in TraceEvent class not in its own class
public class TraceEvent
{
[JsonProperty("attributes")]
public TraceAttributes Attributes { get; set; }
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}
Remove below class
public class TraceCodes
{
public TraceCodes()
{
Codes = new List<TraceCode>();
}
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}
TraceEvent has a property
public TraceCodes Codes { get; set; }
And TraceCodes is another object with a list of codes:
public List<TraceCode> Codes { get; set; }
This would mean there would have to be a structure like this:
{
"TraceEvent": {
"Codes": {
"Codes": [
{ … },
{ … },
}
}
}
}
So the "Codes" part is double. Instead, you need to modify your TraceEvent to have that list directly:
public class TraceEvent
{
[JsonProperty("attributes")]
public TraceAttributes Attributes { get; set; }
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}
Btw. that should have actually resulted in a JsonSerializationException, so you should check whether that gets swallowed somewhere.