Deserializing XML output from an API response - c#

This is the first time I have successfully written code to retrieve XML data from an API call which I then store in a string. I now need to parse that XML string into a class structure in order that I can use it in other parts of my code. This is where I am running into an issue.
The XML string returned from the API is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<OTA_AirDetailsRS
PrimaryLangID="eng"
Version="1.0"
TransactionIdentifier=""
FLSNote="This XML adds attributes not in the OTA XML spec. All such attributes start with FLS"
FLSDevice = "ota-xml-expanded"
xmlns="http://www.opentravel.org/OTA/2003/05">
<Success></Success>
<FLSResponseFields
FLSOriginCode="LHR"
FLSOriginName="Heathrow Airport"
FLSDestinationCode="MAD"
FLSDestinationName="Madrid"
FLSStartDate="2023-01-18"
FLSEndDate="2023-01-18"
FLSResultCount="35"
FLSRoutesFound="155"
FLSBranchCount="3805"
FLSTargetCount="2093"
FLSRecordCount="1280181"
/>
<FlightDetails
TotalFlightTime="PT2H35M"
TotalMiles="775"
TotalTripTime="PT2H35M"
FLSDepartureDateTime="2023-01-18T06:20:00"
FLSDepartureTimeOffset="+0000"
FLSDepartureCode="LHR"
FLSDepartureName="Heathrow Airport"
FLSArrivalDateTime="2023-01-18T09:55:00"
FLSArrivalTimeOffset="+0100"
FLSArrivalCode="MAD"
FLSArrivalName="Madrid"
FLSFlightType="NonStop"
FLSFlightLegs="1"
FLSFlightDays="..3...."
FLSDayIndicator="">
<FlightLegDetails
DepartureDateTime="2023-01-18T06:20:00"
FLSDepartureTimeOffset="+0000"
ArrivalDateTime="2023-01-18T09:55:00"
FLSArrivalTimeOffset="+0100"
FlightNumber="456"
JourneyDuration="PT2H35M"
SequenceNumber="1"
LegDistance="775"
FLSMeals="G"
FLSInflightServices=" "
FLSUUID="LHRMAD20230118BA456"
>
<DepartureAirport
CodeContext="IATA"
LocationCode="LHR"
FLSLocationName="Heathrow Airport"
Terminal="3"
FLSDayIndicator=""
/>
<ArrivalAirport
CodeContext="IATA"
LocationCode="MAD"
FLSLocationName="Adolfo Suarez-Barajas Airport"
Terminal="4S"
FLSDayIndicator=""
/>
<MarketingAirline
Code="BA"
CodeContext="IATA"
CompanyShortName="British Airways"
/>
<Equipment
AirEquipType="320"
/>
</FlightLegDetails>
</FlightDetails>
</OTA_AirDetailsRS>
There could be any number of 'FlightDetails' elements depending on how many flights are returned from the API. Similarly there could be any number of 'FlightLegDetails' elements depending on whether each flight is direct or has a number of stops (denoted by the 'FLSFlightType' attribute under each 'FlightDetails' element.
The class structure I have written is as follows:
public class FlightSearchResults
{
public class searchResults
{
[XmlElement("OTA_AirDetailsRS")]
public List<OTA_AirDetailsRS> OTA_AirDetailsRS { get; set; }
[XmlAttribute("PrimaryLangID")]
public List<success> success { get; set; }
[XmlElement("ResponseFields")]
public List<responseFields> ResponseFields { get; set; }
[XmlElement("FlightDetails")]
public List<flightDetails> FlightDetails { get; set; }
}
public class OTA_AirDetailsRS
{
[XmlAttribute("PrimaryLangID")]
public string PrimaryLangID { get; set; }
[XmlAttribute("Version")]
public string Version { get; set; }
[XmlAttribute("TransactionIdentifier")]
public string TransactionIdentifier { get; set; }
[XmlAttribute("FLSNote")]
public string FLSNote { get; set; }
[XmlAttribute("FLSDevice")]
public string FLSDevice { get; set; }
[XmlAttribute("xmlns")]
public string xmlns { get; set; }
}
public class success
{
[XmlElement("Success")]
public string SuccessIndicator { get; set; }
}
public class responseFields
{
[XmlAttribute("FLSOriginCode")]
public string FLSOriginCode { get; set; }
[XmlAttribute("FLSOriginName")]
public string FLSOriginName { get; set; }
[XmlAttribute("FLSDestinationCode")]
public string FLSDestinationCode { get; set; }
[XmlAttribute("FLSDestinationName")]
public string FLSDestinationName { get; set; }
[XmlAttribute("FLSStartDate")]
public string FLSStartDate { get; set; }
[XmlAttribute("FLSEndDate")]
public string FLSEndDate { get; set; }
[XmlAttribute("FLSResultCount")]
public string FLSResultCount { get; set; }
[XmlAttribute("FLSRoutesFound")]
public string FLSRoutesFound { get; set; }
[XmlAttribute("FLSBranchCount")]
public string FLSBranchCount { get; set; }
[XmlAttribute("FLSTargetCount")]
public string FLSTargetCount { get; set; }
[XmlAttribute("FLSRecordCount")]
public string FLSRecordCount { get; set; }
}
public class flightDetails
{
[XmlAttribute("TotalFlightTime")]
public string TotalFlightTime { get; set; }
[XmlAttribute("TotalMiles")]
public string TotalMiles { get; set; }
[XmlAttribute("TotalTripTime")]
public string TotalTripTime { get; set; }
[XmlAttribute("FLSDepartureDateTime")]
public string FLSDepartureDateTime { get; set; }
[XmlAttribute("FLSDepartureTimeOffset")]
public string FLSDepartureTimeOffset { get; set; }
[XmlAttribute("DepartureCode")]
public string FLSDepartureCode { get; set; }
[XmlAttribute("FLSDepartureName")]
public string FLSDepartureName { get; set; }
[XmlAttribute("FLSArrivalDateTime")]
public string FLSArrivalDateTime { get; set; }
[XmlAttribute("FLSArrivalTimeOffset")]
public string FLSArrivalTimeOffset { get; set; }
[XmlAttribute("FLSArrivalCode")]
public string FLSArrivalCode { get; set; }
[XmlAttribute("FLSArrivalName")]
public string FLSArrivalName { get; set; }
[XmlAttribute("FLSFlightType")]
public string FLSFlightType { get; set; }
[XmlAttribute("FLSFlightLegs")]
public string FLSFlightLegs { get; set; }
[XmlAttribute("FLSFlightDays")]
public string FLSFlightDays { get; set; }
[XmlAttribute("FLSDayIndicator")]
public string FLSDayIndicator { get; set; }
[XmlElement("FlightLegDetails")]
public List<flightLegDetails> FlightLegDetails { get; set; }
}
public class flightLegDetails
{
[XmlAttribute("DepartureDateTime")]
public string DepartureDateTime { get; set; }
[XmlAttribute("FLSDepartureTimeOffset")]
public string FLSDepartureTimeOffset{ get; set; }
[XmlAttribute("ArrivalDateTime")]
public string ArrivalDateTime { get; set; }
[XmlAttribute("ArrivalTimeOffset")]
public string ArrivalTimeOffset { get; set; }
[XmlAttribute("FlightNumber")]
public string FlightNumber { get; set; }
[XmlAttribute("JourneyDuration")]
public string JourneyDuration { get; set; }
[XmlAttribute("SequenceNumber")]
public string SequenceNumber { get; set; }
[XmlAttribute("LegDistance")]
public string LegDistance { get; set; }
[XmlAttribute("FLSMeals")]
public string FLSMeals { get; set; }
[XmlAttribute("FLSInflightServices")]
public string FLSInflightServices { get; set; }
[XmlAttribute("FLSUUND")]
public string FLSUUID { get; set; }
[XmlElement("DepartureAirport")]
public List<departureAirport> DepartureAirport { get; set; }
[XmlElement("ArrivalAirport")]
public List<arrivalAirport> ArrivalAirport { get; set; }
[XmlElement("MarketingAirline")]
public List<marketingAirline> MarketingAirline { get; set; }
[XmlAttribute("AirEquipType")]
public string AirEquipType { get; set; }
}
public class departureAirport
{
[XmlAttribute("CodeContext")]
public string CodeContext { get; set; }
[XmlAttribute("LocationCode")]
public string LocationCode { get; set; }
[XmlAttribute("FLSLocationName")]
public string FLSLocationName { get; set; }
[XmlAttribute("Terminal")]
public string Terminal { get; set; }
[XmlAttribute("FLSDayIndicator")]
public string FLSDayIndicator { get; set; }
}
public class arrivalAirport
{
[XmlAttribute("CodeContext")]
public string CodeContext { get; set; }
[XmlAttribute("LocationCode")]
public string LocationCode { get; set; }
[XmlAttribute("FLSLocationName")]
public string FLSLocationName { get; set; }
[XmlAttribute("Terminal")]
public string Terminal { get; set; }
[XmlAttribute("FLSDayIndicator")]
public string FLSDayIndicator { get; set; }
}
public class marketingAirline
{
[XmlAttribute("Code")]
public string Code { get; set; }
[XmlAttribute("CodeContext")]
public string CodeContext { get; set; }
[XmlAttribute("CompanyShortName")]
public string CompanyShortName { get; set; }
}
public static List<FlightSearchResults> flightSearchRes = new List<FlightSearchResults>();
}
And the code to parse the XML string is:
public static object XmlDeserializeFromString(this string objectData, Type type)
{
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
return result;
}
which I call via:
FlightSearchResults.flightSearchRes = (List<FlightSearchResults>)Functions.XmlDeserializeFromString(xmlRes, xmlRes.GetType());
The error occurs on the 'result = serializer.Deserialize(reader);' line of the XmlDeserializeFromString function - '<OTA_AirDetailsRS xmlns='http://www.opentravel.org/OTA/2003/05'> was not expected.'. Full error details below:
System.InvalidOperationException
HResult=0x80131509
Message=There is an error in XML document (2, 2).
Source=System.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
at World_Airport_Details.Functions.XmlDeserializeFromString(String objectData, Type type) in C:\Users\Chris\source\repos\World Airport Details\World Airport Details\Functions.cs:line 600
at World_Airport_Details.DetailsWindow.btnSearchFlights_Click(Object sender, RoutedEventArgs e) in C:\Users\Chris\source\repos\World Airport Details\World Airport Details\DetailsWindow.xaml.cs:line 5455
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Window.ShowHelper(Object booleanBox)
at System.Windows.Window.Show()
at System.Windows.Window.ShowDialog()
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1:
InvalidOperationException: <OTA_AirDetailsRS xmlns='http://www.opentravel.org/OTA/2003/05'> was not expected.
Can anyone help me with this as all google searches I have made have not been successful.
Many thanks
Chris
Tried moving the xmlns line to line 2 of the XML string before parsing
Tried adding [XmlIgnore] before the 'xmlns' property in the class structure
Tried adding an [XmlRoot] of 'OTA_AirDetailsRS' to the top of the class structure

A few points of interest before we proceed:
(1) There should be exactly ONE root element
This is the XML standard:
"There is exactly one element, called the root, or document element, no part of which appears in the content of any other element".
In your case, that would be OTA_AirDetailsRS. It will be your top level class, and you should never get a List<OTA_AirDetailsRS> from a single valid XML.
(2) xmlns is a namespace.
There is a rather long reading about namespaces in the XML standard.
But in short, just like namespaces in your C# code, it is there to ensure uniqueness.
It's not treated like a normal xml attribute.
(3) In C#, an XML attribute/element defaults to the name of the property/field.
I.e. instead of writing [XmlAttribute("Version")] string Version; you could simply do [XmlAttribute] string Version;. Unless you name them differently in your class vs in the XML.
* Also note, you may have to review where you are using List<>. E.g. does it really make sense to have multiple DepartureAirport on a single leg?
Now that that's out of the way, the following fragment works against your XML:
public static void Main() {
var airDetails = DeserializeFromString<OTA_AirDetailsRS>(yourXmlStringHere);
// .. do stuff
}
public static T DeserializeFromString<T>(string xml) {
// You need deserialize your ROOT class: OTA_AirDetailsRS
var serializer = new XmlSerializer(typeof(T));
using var reader = new StringReader(xml);
return (T)serializer.Deserialize(reader);
}
// This is your root. You specify it as an `XmlRoot()`.
// `xmlns` should go here as `Namespace`.
[XmlRoot(Namespace = "http://www.opentravel.org/OTA/2003/05")]
public class OTA_AirDetailsRS {
[XmlAttribute] public string PrimaryLangID { get; set; }
[XmlAttribute] public string Version { get; set; }
[XmlAttribute] public string TransactionIdentifier { get; set; }
[XmlAttribute] public string FLSNote { get; set; }
[XmlAttribute] public string FLSDevice { get; set; }
[XmlElement] public responseFields FLSResponseFields { get; set; }
[XmlElement] public List<flightDetails> FlightDetails { get; set; }
}
// ----- The rest of these are nothing special -----
public class success {
[XmlElement] public string SuccessIndicator { get; set; }
}
public class responseFields {
[XmlAttribute] public string FLSOriginCode { get; set; }
[XmlAttribute] public string FLSOriginName { get; set; }
[XmlAttribute] public string FLSDestinationCode { get; set; }
[XmlAttribute] public string FLSDestinationName { get; set; }
[XmlAttribute] public string FLSStartDate { get; set; }
[XmlAttribute] public string FLSEndDate { get; set; }
[XmlAttribute] public string FLSResultCount { get; set; }
[XmlAttribute] public string FLSRoutesFound { get; set; }
[XmlAttribute] public string FLSBranchCount { get; set; }
[XmlAttribute] public string FLSTargetCount { get; set; }
[XmlAttribute] public string FLSRecordCount { get; set; }
}
public class flightDetails {
[XmlAttribute] public string TotalFlightTime { get; set; }
[XmlAttribute] public string TotalMiles { get; set; }
[XmlAttribute] public string TotalTripTime { get; set; }
[XmlAttribute] public string FLSDepartureDateTime { get; set; }
[XmlAttribute] public string FLSDepartureTimeOffset { get; set; }
[XmlAttribute] public string FLSDepartureCode { get; set; }
[XmlAttribute] public string FLSDepartureName { get; set; }
[XmlAttribute] public string FLSArrivalDateTime { get; set; }
[XmlAttribute] public string FLSArrivalTimeOffset { get; set; }
[XmlAttribute] public string FLSArrivalCode { get; set; }
[XmlAttribute] public string FLSArrivalName { get; set; }
[XmlAttribute] public string FLSFlightType { get; set; }
[XmlAttribute] public string FLSFlightLegs { get; set; }
[XmlAttribute] public string FLSFlightDays { get; set; }
[XmlAttribute] public string FLSDayIndicator { get; set; }
[XmlElement] public List<flightLegDetails> FlightLegDetails { get; set; }
}
public class flightLegDetails {
[XmlAttribute] public string DepartureDateTime { get; set; }
[XmlAttribute] public string FLSDepartureTimeOffset { get; set; }
[XmlAttribute] public string ArrivalDateTime { get; set; }
[XmlAttribute] public string FLSArrivalTimeOffset { get; set; }
[XmlAttribute] public string FlightNumber { get; set; }
[XmlAttribute] public string JourneyDuration { get; set; }
[XmlAttribute] public string SequenceNumber { get; set; }
[XmlAttribute] public string LegDistance { get; set; }
[XmlAttribute] public string FLSMeals { get; set; }
[XmlAttribute] public string FLSInflightServices { get; set; }
[XmlAttribute] public string FLSUUID { get; set; }
[XmlElement] public List<departureAirport> DepartureAirport { get; set; }
[XmlElement] public List<arrivalAirport> ArrivalAirport { get; set; }
[XmlElement] public List<marketingAirline> MarketingAirline { get; set; }
[XmlAttribute] public string AirEquipType { get; set; }
}
public class departureAirport {
[XmlAttribute] public string CodeContext { get; set; }
[XmlAttribute] public string LocationCode { get; set; }
[XmlAttribute] public string FLSLocationName { get; set; }
[XmlAttribute] public string Terminal { get; set; }
[XmlAttribute] public string FLSDayIndicator { get; set; }
}
public class arrivalAirport {
[XmlAttribute] public string CodeContext { get; set; }
[XmlAttribute] public string LocationCode { get; set; }
[XmlAttribute] public string FLSLocationName { get; set; }
[XmlAttribute] public string Terminal { get; set; }
[XmlAttribute] public string FLSDayIndicator { get; set; }
}
public class marketingAirline {
[XmlAttribute] public string Code { get; set; }
[XmlAttribute] public string CodeContext { get; set; }
[XmlAttribute] public string CompanyShortName { get; set; }
}

Related

How can I convert a StringContent() type to an object of type <MyModelClass> in C# with Visual Studio 2019

I'm trying to turn the string result below in the first line of code into an object of type "Root.cs". I have "Root.cs" class set up in my Visual Studio 2019 "solution" with proper classes set up to turn the string result into the object.
This line of code works fine to get me the string I need:
var result = client.PostAsync(endpoint, payload).Result.Content.ReadAsStringAsync().Result;
Here's the contents of the string "result":
{"sections":[{"id":"Building_Configuration","name":"Building_Configuration","sections":[{"id":"B uilding_Configuration.Parameters_SP","name":"Building_Configuration.Parameters_SP","sectio ns":[],"variables":[{"id":"Building_Configuration.Parameters_SP.fixtureStrategy_SP","name":"Bui lding_Configuration.Parameters_SP.fixtureStrategy_SP","valueType":"String","distinctValueCou nt":3.0,"allowMultipleAssignments":false,"values":[{"name":"ETA","value":"ETA","properties":[{ "id":"fullyqualifiedname","value":"ETA","type":"String"},{"id":"name","value":"ETA","type":"Stri ng"}],"type":"SingletonValue","assigned":"byDefault","incompatible":false},{"name":"ETD","valu e":"ETD","properties":[{"id":"fullyqualifiedname","value":"ETD","type":"String"},{"id":"name","v alue":"ETD","type":"String"}],"type":"SingletonValue","incompatible":false},{"name":"ETA/ETD", "value":"ETA/ETD","properties":[{"id":"fullyqualifiedname","value":"ETA/ETD","type":"String"},{ "id":"name","value":"ETA/ETD","type":"String"}],"type":"SingletonValue","incompatible":false}],"
Now, I need to create the object of type "Root" (My Model Class) for the purpose of picking and choosing certain values out of it. Shouldn't this line work for that?
Root MyObject = JsonConvert.DeserializeObject<Root>(result);
Here's the definition of Root.cs:
public class Root
{
public List<Sections> sections { get; set; }
public RemovedAssignments removedAssignments { get; set; }
public Arguments arguments { get; set; }
public bool isComplete { get; set; }
public bool isConfigurable { get; set; }
public Debug debug { get; set; }
public string language { get; set; }
public string packagePath { get; set; }
}
public class Sections
{
public string id { get; set; }
public string name { get; set; }
public List<Sections> sections { get; set; }
public List<Variable> variables { get; set; }
public List<Property> properties { get; set; }
}
public class RemovedAssignments
{
public List<VariableAssignment> variableAssignments { get; set; }
public List<object> priceLineAssignments { get; set; }
}
public class Debug
{
public List<ScriptError> scriptError { get; set; }
}
public class Property
{
public string id { get; set; }
public string value { get; set; }
public string type { get; set; }
}
public class ScriptError
{
public string scriptName { get; set; }
public string Error { get; set; }
}
public class Value
{
public string name { get; set; }
public object value { get; set; }
public List<Property> properties { get; set; }
public string type { get; set; }
public string assigned { get; set; }
public bool incompatible { get; set; }
public double? lower { get; set; }
public double? upper { get; set; }
}
public class Value3
{
public string value { get; set; }
public string name { get; set; }
public bool exclude { get; set; }
}
public class Variable
{
public string id { get; set; }
public string name { get; set; }
public string valueType { get; set; }
public double distinctValueCount { get; set; }
public bool allowMultipleAssignments { get; set; }
public List<Value> values { get; set; }
public List<Property> properties { get; set; }
}
public class Variable3
{
public string id { get; set; }
public string name { get; set; }
public string valueType { get; set; }
public bool allowMultipleAssignments { get; set; }
}
public class VariableAssignment
{
public Variable variable { get; set; }
public Value value { get; set; }
}
public class Arguments
{
public Configuration Configuration { get; set; }
}
public class Configuration
{
[JsonProperty("Building_Configuration.Parameters_SP.fixtureStrategy_SP")]
public string BuildingConfigurationParametersSPFixtureStrategySP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.dimensionSelection_SP")]
public string BuildingConfigurationParametersSPDimensionSelectionSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.controllerRobotic_SP")]
public bool BuildingConfigurationParametersSPControllerRoboticSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.controllerBACNet_SP")]
public bool BuildingConfigurationParametersSPControllerBACNetSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.digitalPI_SP")]
public string BuildingConfigurationParametersSPDigitalPISP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.interGroupEmergencyPower_SP")]
public string BuildingConfigurationParametersSPInterGroupEmergencyPowerSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.customJewel_SP")]
public string BuildingConfigurationParametersSPCustomJewelSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.loweringSequenceJewel_SP")]
public string BuildingConfigurationParametersSPLoweringSequenceJewelSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.inServiceJewel_SP")]
public string BuildingConfigurationParametersSPInServiceJewelSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.cat5CableFeetRequired_SP")]
public int BuildingConfigurationParametersSPCat5CableFeetRequiredSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.fiberOpticConnectorsSetOf4_SP")]
public int BuildingConfigurationParametersSPFiberOpticConnectorsSetOf4SP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.cGADevices_SP")]
public int BuildingConfigurationParametersSPCGADevicesSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.fiberOpticCableFeetRequired_SP")]
public int BuildingConfigurationParametersSPFiberOpticCableFeetRequiredSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfGatewayForLiftNet_SP")]
public int BuildingConfigurationParametersSPQtyOfGatewayForLiftNetSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfGroupEthernetBoxWIMSSoftwareOnly_SP")]
public int BuildingConfigurationParametersSPQtyOfGroupEthernetBoxWIMSSoftwareOnlySP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.interGroupStarBox_SP")]
public int BuildingConfigurationParametersSPInterGroupStarBoxSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.mediaConverterAndPowerSource_SP")]
public int BuildingConfigurationParametersSPMediaConverterAndPowerSourceSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfSoftwareSiteKeyJBFiles_SP")]
public int BuildingConfigurationParametersSPQtyOfSoftwareSiteKeyJBFilesSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.doorOpenSignalJewel_SP")]
public bool BuildingConfigurationParametersSPDoorOpenSignalJewelSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.mountingProvisionsForMonitor_SP")]
public bool BuildingConfigurationParametersSPMountingProvisionsForMonitorSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.intercomSpace_SP")]
public bool BuildingConfigurationParametersSPIntercomSpaceSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.specialEngraving_SP")]
public bool BuildingConfigurationParametersSPSpecialEngravingSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.lobbyPanelFinish_SP")]
public string BuildingConfigurationParametersSPLobbyPanelFinishSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.includeAGILEDesignCenter_SP")]
public int BuildingConfigurationParametersSPIncludeAGILEDesignCenterSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyKiosksOver300Ft_SP")]
public int BuildingConfigurationParametersSPQtyKiosksOver300FtSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.dDSecurityInterfaceType_SP")]
public bool BuildingConfigurationParametersSPDDSecurityInterfaceTypeSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.iMSOwnersStandard_SP")]
public int BuildingConfigurationParametersSPIMSOwnersStandardSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfIMSOwnersEnhanced_SP")]
public int BuildingConfigurationParametersSPQtyOfIMSOwnersEnhancedSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.totalGroupHallStation_SP")]
public int BuildingConfigurationParametersSPTotalGroupHallStationSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.totalUnitHallStation_SP")]
public int BuildingConfigurationParametersSPTotalUnitHallStationSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.totalBuildingEquip_SP")]
public int BuildingConfigurationParametersSPTotalBuildingEquipSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.IsSmartRescue10_Bool_SP")]
public bool BuildingConfigurationParametersSPIsSmartRescue10BoolSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.IsSmartRescue5_Bool_SP")]
public bool BuildingConfigurationParametersSPIsSmartRescue5BoolSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.lobbyPanel_SP")]
public string BuildingConfigurationParametersSPLobbyPanelSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfSmartRescuePhone10_StndAlone_SP")]
public int BuildingConfigurationParametersSPQtyOfSmartRescuePhone10StndAloneSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfSmartRescuePhone5_Lobby_SP")]
public int BuildingConfigurationParametersSPQtyOfSmartRescuePhone5LobbySP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfSmartRescuePhone5_StndAlone_SP")]
public int BuildingConfigurationParametersSPQtyOfSmartRescuePhone5StndAloneSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfSmartRescuePhone10_Lobby_SP")]
public int BuildingConfigurationParametersSPQtyOfSmartRescuePhone10LobbySP { get; set; }
[JsonProperty("Building_Configuration.Parameters.ASYEAR_INT")]
public int BuildingConfigurationParametersASYEARINT { get; set; }
[JsonProperty("Building_Configuration.Parameters.BLANDINGS")]
public int BuildingConfigurationParametersBLANDINGS { get; set; }
[JsonProperty("Building_Configuration.Parameters.ASTYPE")]
public string BuildingConfigurationParametersASTYPE { get; set; }
[JsonProperty("Building_Configuration.Parameters.ASYEAR")]
public string BuildingConfigurationParametersASYEAR { get; set; }
[JsonProperty("Building_Configuration.Parameters.BLDGNAME")]
public string BuildingConfigurationParametersBLDGNAME { get; set; }
[JsonProperty("Building_Configuration.Parameters.IBCSDS")]
public int BuildingConfigurationParametersIBCSDS { get; set; }
[JsonProperty("Building_Configuration.Parameters.ELEVBASE")]
public int BuildingConfigurationParametersELEVBASE { get; set; }
[JsonProperty("Building_Configuration.Parameters.SEISZONE")]
public string BuildingConfigurationParametersSEISZONE { get; set; }
[JsonProperty("Building_Configuration.Parameters.SEISEQUIP")]
public string BuildingConfigurationParametersSEISEQUIP { get; set; }
[JsonProperty("Building_Configuration.Parameters.ISSEISMIC")]
public string BuildingConfigurationParametersISSEISMIC { get; set; }
[JsonProperty("Building_Configuration.Parameters.IBCSDC")]
public string BuildingConfigurationParametersIBCSDC { get; set; }
[JsonProperty("Building_Configuration.Parameters.IBCIP")]
public string BuildingConfigurationParametersIBCIP { get; set; }
[JsonProperty("Building_Configuration.Parameters.NBCCPDB")]
public string BuildingConfigurationParametersNBCCPDB { get; set; }
[JsonProperty("Building_Configuration.Parameters.NBCCIE")]
public int BuildingConfigurationParametersNBCCIE { get; set; }
[JsonProperty("Building_Configuration.Parameters.NBCCFA")]
public int BuildingConfigurationParametersNBCCFA { get; set; }
[JsonProperty("Building_Configuration.Parameters.NBCCSA02")]
public int BuildingConfigurationParametersNBCCSA02 { get; set; }
[JsonProperty("Building_Configuration.Parameters.BLDGCODE")]
public string BuildingConfigurationParametersBLDGCODE { get; set; }
[JsonProperty("Building_Configuration.Parameters.HALLFIN")]
public string BuildingConfigurationParametersHALLFIN { get; set; }
[JsonProperty("Building_Configuration.Parameters.MRP")]
public string BuildingConfigurationParametersMRP { get; set; }
[JsonProperty("Building_Configuration.Parameters.HALLMAT")]
public string BuildingConfigurationParametersHALLMAT { get; set; }
My "result" and my "Root.cs" class are each larger than the 30,000 characters limit here. So, I've had to only post a portion of my string "result" and my "Root.cs" class. I'm trying to simplify this question. Please forgive me while I learn how to use this...
Answer: I was making the newbie mistake of trying to return a string that I picked out of a "Root.cs" Model class as a Root object. I had the return type of the method set to Root instead of string. Upon changing the return type to string, that part of my solution works fine.
It works fine like this:
public string CreateExecPost(FormData person2){
var payload = new StringContent(newPost, Encoding.UTF8, "application/json");
var result = client.PostAsync(endpoint, payload).Result.Content.ReadAsStringAsync().Result;//result is already in JSON
Root MyObject = JsonConvert.DeserializeObject<Root>(result);
//return MyObject.language; //WORKS
return MyObject.language;
}

C# Reading json and edit

SOLUTION
Profile newProfileList = new Profile();
newProfileList = myDeserializedClass.profiles[0]; // New profile list is null so i've casted some values from old ones.
myDeserializedClass.profiles.Add(newProfileList);
richTextBox1.Text = JsonConvert.SerializeObject(myDeserializedClass);
Then i can save it as json file again. Thanks to #Donut
I've got the following code:
OpenFileDialog ofd = new OpenFileDialog();
string txtProfile;
if (ofd.ShowDialog() == DialogResult.OK)
{
txtProfile = File.ReadAllText(ofd.FileName);
richTextBox1.Text = txtProfile;
}
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(richTextBox1.Text);
Using this code, I'm able to read a JSON file and deserialize it successfully to an instance of the Root class. However, when I try to create new profiles in this object, I get some error about "read only values":
Form1.cs(124,13,124,47): error CS0200: Property or indexer 'List<Form1.Profile>.Count' cannot be assigned to -- it is read only
How can I correctly edit the deserialized data (e.g. add new instances of the Profile class), and save it back to the JSON file?
For reference, here are the classes I'm using for deserialization.
public class Metadata
{
public string app_flavor { get; set; }
public int app_version { get; set; }
}
public class Profile
{
public int ajax_connections_limit { get; set; }
public bool allow_emulator_ua_detection { get; set; }
public string apply_css_patches { get; set; }
public bool created_by_user { get; set; }
public string custom_user_agent { get; set; }
public bool device_custom_dev_id2 { get; set; }
public string device_id { get; set; }
public string device_id2 { get; set; }
public string device_id_seed { get; set; }
public string device_signature { get; set; }
public string display_resolution { get; set; }
public bool enable_ministra_compatibility { get; set; }
public bool external_player_send_back_key_event { get; set; }
public bool external_player_send_exit_key_event { get; set; }
public bool external_player_send_key_event { get; set; }
public bool external_player_send_ok_key_event { get; set; }
public string firmware { get; set; }
public string firmware_js_api_ver { get; set; }
public string firmware_player_engine_ver { get; set; }
public string firmware_stb_api_ver { get; set; }
public bool fix_ajax { get; set; }
public bool fix_background_color { get; set; }
public bool fix_local_file_scheme { get; set; }
public bool front_panel { get; set; }
public int generic_connections_limit { get; set; }
public string hardware_vendor { get; set; }
public string hardware_version { get; set; }
public string image_date { get; set; }
public string image_description { get; set; }
public string image_version { get; set; }
public string internal_portal_url { get; set; }
public bool is_internal_portal { get; set; }
public int lang_audiotracks { get; set; }
public int lang_subtitles { get; set; }
public string language { get; set; }
public bool limit_max_connections { get; set; }
public string mac_address { get; set; }
public string mac_seed_net_interface { get; set; }
public string media_player { get; set; }
public bool media_player_per_channel { get; set; }
public string name { get; set; }
public string ntp_server { get; set; }
public string overwrite_stream_protocol { get; set; }
public string playlist_charset { get; set; }
public string portal_url { get; set; }
public string proxy_host { get; set; }
public int proxy_port { get; set; }
public bool send_device_id { get; set; }
public string serial_number { get; set; }
public bool show_player_name { get; set; }
public string stb_internal_config { get; set; }
public string stb_model { get; set; }
public bool subtitles_on { get; set; }
public string tasks_data { get; set; }
public bool timeshift_enabled { get; set; }
public string timeshift_path { get; set; }
public string timezone { get; set; }
public bool udpxy_enabled { get; set; }
public string udpxy_url { get; set; }
public bool use_alt_stalker_auth_dialog { get; set; }
public bool use_alternative_web_view_scale_method { get; set; }
public bool use_browser_redirection { get; set; }
public bool use_custom_user_agent { get; set; }
public bool use_extended_mag_api { get; set; }
public bool use_http_proxy { get; set; }
public bool use_mac_based_device_id { get; set; }
public string user_agent { get; set; }
public string uuid { get; set; }
public string video_resolution { get; set; }
public int video_resume_time { get; set; }
public string weather_place { get; set; }
public bool web_proxy_enabled { get; set; }
}
public class Root
{
public Metadata metadata { get; set; }
public List<Profile> profiles { get; set; }
}

Json string deserialization C#

I have this json
and i want to deserialize it so I can get each object's value for example:
"icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpouLWzKjhzw8zFdC5K092kl5SClMj3PLXFhGpC_Pp8j-3I4IG7i1Hn_UI-Nmj3ItDGe1BoN1mCr1G4xL_vhMS8tcmcn3JhuihwsHvbzQv3309k3tBw8A",
The problem is I can make the class(es) that I need so I can deserialize the json because the json string has nested objects.
I used json2csharp to help me generate classes. After some merging and cleaning up, this is what I got:
public class InventoryItem
{
public string id { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string amount { get; set; }
public int pos { get; set; }
}
public class AppData
{
public string def_index { get; set; }
public int? is_itemset_name { get; set; }
public int? limited { get; set; }
}
public class Description
{
public string type { get; set; }
public string value { get; set; }
public string color { get; set; }
public AppData app_data { get; set; }
}
public class Action
{
public string name { get; set; }
public string link { get; set; }
}
public class Tag
{
public string internal_name { get; set; }
public string name { get; set; }
public string category { get; set; }
public string category_name { get; set; }
public string color { get; set; }
}
public class RgDescription
{
public string appid { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string icon_url { get; set; }
public string icon_url_large { get; set; }
public string icon_drag_url { get; set; }
public string name { get; set; }
public string market_hash_name { get; set; }
public string market_name { get; set; }
public string name_color { get; set; }
public string background_color { get; set; }
public string type { get; set; }
public int tradable { get; set; }
public int marketable { get; set; }
public int commodity { get; set; }
public string market_tradable_restriction { get; set; }
public List<Description> descriptions { get; set; }
public List<Action> actions { get; set; }
public List<Action> market_actions { get; set; }
public List<Tag> tags { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public IDictionary<string, InventoryItem> rgInventory { get; set; }
public List<object> rgCurrency { get; set; }
public IDictionary<string, RgDescription> rgDescriptions { get; set; }
public bool more { get; set; }
public bool more_start { get; set; }
}
These appear to work correctly, you can deserialize and serialize with code like this:
var obj = JsonConvert.DeserializeObject<RootObject>(oldString);
Console.WriteLine(obj.rgDescriptions["310776560_302028390"].icon_url); // e.g.
var newString = JsonConvert.SerializeObject(obj,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// null value handling is optional, the above makes it a little more like the source string

The required property {0} does not exist on the type {1}. Entity framework (model first) when adding FK

I am trying to add foreign key to the database and then I am updating the model. After I update the model, the application gives following error:
System.Data.Entity.Core.MetadataException was unhandled
HResult=-2146232007
Message=Schema specified is not valid. Errors:
The relationship 'Accounting.Data.Repository.FK_np_DocumentStatuses_DocumentsTracking_StateId' was not loaded because the type 'Accounting.Data.Repository.DocumentsTracking' is not available.
The following information may be useful in resolving the previous error:
The required property 'DocumentsTrackingChildDocuments' does not exist on the type 'Accounting.Entity.DocumentsTracking'.
The relationship 'Accounting.Data.Repository.FK_np_DocumentsTracking_DocumentsTrackingChildDocuments_DocumentsTrackingId' was not loaded because the type 'Accounting.Data.Repository.DocumentsTracking' is not available.
The following information may be useful in resolving the previous error:
The required property 'DocumentsTrackingChildDocuments' does not exist on the type 'Accounting.Entity.DocumentsTracking'.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(Assembly assembly, Boolean loadReferencedAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage)
at System.Data.Entity.Core.Metadata.Edm.ObjectItemCollection.ExplicitLoadFromAssembly(Assembly assembly, EdmItemCollection edmItemCollection, Action`1 logLoadMessage)
at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.ExplicitLoadFromAssembly(Assembly assembly, ObjectItemCollection collection, Action`1 logLoadMessage)
at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.LoadFromAssembly(Assembly assembly, Action`1 logLoadMessage)
at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.LoadFromAssembly(Assembly assembly)
at System.Data.Entity.Core.Metadata.Edm.MetadataOptimization.TryUpdateEntitySetMappingsForType(Type entityType)
at System.Data.Entity.Internal.InternalContext.TryUpdateEntitySetMappingsForType(Type entityType)
at System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType)
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Accounting.Data.Logic.OrdersLogic.getOrdersTmpList() in f:\proj\Accounting.Data.Logic\OrdersLogic.cs:line 16
at Accounting.Data.Logic.OrdersLogic.RefreshDocumentsFromTmpOrders() in f:\proj\Accounting.Data.Logic\OrdersLogic.cs:line 22
at Accounting.UI.MainForm.btnRefreshDocumentsFromOrderTmp_Click(Object sender, EventArgs e) in f:\proj\Accounting.UI\MainForm.cs:line 57
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Accounting.UI.Program.Main() in f:\proj\Accounting.UI\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
My entities:
namespace Iwatch.Accounting.Entity
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Xml.Serialization;
public partial class DocumentStatus
{
public DocumentStatus()
{
this.Documents = new HashSet<Document>();
this.DocumentsTrackings = new HashSet<DocumentsTracking>();
this.DocumentsTrackingChildDocuments = new HashSet<DocumentsTrackingChildDocument>();
}
[XmlElement("StateId")]
[Key]
public int StateId { get; set; }
[XmlElement("StateName")]
public string StateName { get; set; }
[XmlElement("GroupId")]
public Nullable<int> GroupId { get; set; }
public virtual HashSet<Document> Documents { get; set; }
public virtual HashSet<DocumentsTracking> DocumentsTrackings { get; set; }
public virtual HashSet<DocumentsTrackingChildDocument> DocumentsTrackingChildDocuments { get; set; }
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Iwatch.Accounting.Entity
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Xml.Serialization;
public partial class DocumentsTracking
{
[XmlIgnore]
CultureInfo culture = CultureInfo.CreateSpecificCulture("de-LI");
[XmlIgnore]
public int Id { get; set; }
[Key]
[XmlElement("Barcode")]
public string Barcode { get; set; }
[XmlElement("StateId")]
public Nullable<int> StateId { get; set; }
[XmlElement("StateName")]
public string StateName { get; set; }
[XmlElement("CheckWeight")]
public Nullable<decimal> CheckWeight { get; set; }
[XmlElement("DocumentCost")]
public Nullable<decimal> DocumentCost { get; set; }
[XmlIgnore]
public DateTime? DateReceived { get; set; }
[XmlElement("DateReceived")]
public string DateReceivedString
{
get { return this.DateReceived != null ? this.DateReceived.Value.ToString("dd.MM.yyyy hh:mm:ss") : ""; }
set { this.DateReceived = (value.Equals("") ? (DateTime?)null : System.DateTime.Parse(value, culture)); }
}
[XmlElement("RecipientFullName")]
public string RecipientFullName { get; set; }
[XmlElement("RecipientPost")]
public string RecipientPost { get; set; }
[XmlIgnore]
public DateTime? ReceiptDateTime { get; set; }
[XmlElement("ReceiptDateTime")]
public string ReceiptDateTimeString
{
get { return this.ReceiptDateTime != null ? this.ReceiptDateTime.Value.ToString("yyyy-MM-dd hh:mm:ss") : ""; }
set { this.ReceiptDateTime = (value.Equals("") ? (DateTime?)null : System.DateTime.Parse(value)); }
}
[XmlElement("OnlinePayment")]
public Nullable<bool> OnlinePayment { get; set; }
[XmlElement("DeliveryForm")]
public Nullable<int> DeliveryForm { get; set; }
[XmlElement("AddressUA")]
public string AddressUA { get; set; }
[XmlElement("AddressRU")]
public string AddressRU { get; set; }
[XmlElement("WareReceiverId")]
public Nullable<int> WareReceiverId { get; set; }
[XmlElement("BackDelivery")]
public Nullable<int> BackDelivery { get; set; }
[XmlElement("RedeliveryNUM")]
public string RedeliveryNUM { get; set; }
[XmlElement("CityReceiverSiteKey")]
public Nullable<int> CityReceiverSiteKey { get; set; }
[XmlElement("CityReceiverUA")]
public string CityReceiverUA { get; set; }
[XmlElement("CityReceiverRU")]
public string CityReceiverRU { get; set; }
[XmlElement("CitySenderSiteKey")]
public Nullable<int> CitySenderSiteKey { get; set; }
[XmlElement("CitySenderUA")]
public string CitySenderUA { get; set; }
[XmlElement("CitySenderRU")]
public string CitySenderRU { get; set; }
[XmlElement("DeliveryType")]
public string DeliveryType { get; set; }
[XmlElement("BackwardDeliveryNumber")]
public System.Guid BackwardDeliveryNumber { get; set; }
[XmlElement("RedeliveryCargoDescriptionMoney")]
public string RedeliveryCargoDescriptionMoney { get; set; }
[XmlElement("Failure")]
public Nullable<bool> Failure { get; set; }
[XmlElement("ReasonDescription")]
public string ReasonDescription { get; set; }
[XmlElement("GlobalMoneyExistDelivery")]
public Nullable<bool> GlobalMoneyExistDelivery { get; set; }
[XmlElement("GlobalMoneyLastTransactionStatus")]
public string GlobalMoneyLastTransactionStatus { get; set; }
[XmlIgnore]
public DateTime? GlobalMoneyLastTransactionDate { get; set; }
[XmlElement("GlobalMoneyLastTransactionDate")]
public string GlobalMoneyLastTransactionDateString
{
get { return this.GlobalMoneyLastTransactionDate != null ? this.GlobalMoneyLastTransactionDate.Value.ToString("yyyy-MM-dd hh:mm:ss") : ""; }
set { this.GlobalMoneyLastTransactionDate = (value.Equals("") ? (DateTime?)null : System.DateTime.Parse(value)); }
}
[XmlElement("Sum")]
public Nullable<decimal> Sum { get; set; }
[XmlElement("DocumentWeight")]
public Nullable<decimal> DocumentWeight { get; set; }
//TODO: the right data type is supposed to be used
[XmlIgnore] //[XmlElement("SumBeforeCheckWeight")]
public Nullable<decimal> SumBeforeCheckWeight { get; set; }
[XmlElement("isEWPaid")]
public Nullable<bool> isEWPaid { get; set; }
[XmlElement("isEWPaidCashLess")]
public Nullable<bool> isEWPaidCashLess { get; set; }
[XmlElement("ewPaidSumm")]
public Nullable<decimal> ewPaidSumm { get; set; }
[XmlElement("RedeliverySum")]
public Nullable<decimal> RedeliverySum { get; set; }
[XmlElement("OwnerDocumentType")]
public string OwnerDocumentType { get; set; }
[XmlElement("errors")]
public string errors { get; set; }
[XmlElement("warnings")]
public string warnings { get; set; }
[XmlElement("info")]
public string info { get; set; }
public virtual DocumentStatus DocumentStatus { get; set; }
public virtual DocumentsTrackingChildDocument DocumentsTrackingChildDocument { get; set; }
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Iwatch.Accounting.Entity
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Xml.Serialization;
public partial class DocumentsTrackingChildDocument
{
public int Id { get; set; }
[XmlElement("DocumentsTrackingId")]
[Key]
public Nullable<int> DocumentsTrackingId { get; set; }
[XmlElement("Barcode")]
public string Barcode { get; set; }
[XmlElement("StateId")]
public Nullable<int> StateId { get; set; }
[XmlElement("StateName")]
public string StateName { get; set; }
[XmlElement("CheckWeight")]
public Nullable<decimal> CheckWeight { get; set; }
[XmlElement("DocumentCost")]
public Nullable<decimal> DocumentCost { get; set; }
[XmlElement("DateReceived")]
public Nullable<System.DateTime> DateReceived { get; set; }
[XmlElement("RecipientFullName")]
public string RecipientFullName { get; set; }
[XmlElement("RecipientPost")]
public string RecipientPost { get; set; }
[XmlElement("ReceiptDateTime")]
public Nullable<System.DateTime> ReceiptDateTime { get; set; }
[XmlElement("OnlinePayment")]
public Nullable<bool> OnlinePayment { get; set; }
[XmlElement("DeliveryForm")]
public string DeliveryForm { get; set; }
[XmlElement("AddressUA")]
public string AddressUA { get; set; }
[XmlElement("AddressRU")]
public string AddressRU { get; set; }
[XmlElement("WareReceiverId")]
public Nullable<int> WareReceiverId { get; set; }
[XmlElement("BackDelivery")]
public string BackDelivery { get; set; }
[XmlElement("RedeliveryNUM")]
public string RedeliveryNUM { get; set; }
[XmlElement("CityReceiverSiteKey")]
public string CityReceiverSiteKey { get; set; }
[XmlElement("CityReceiverUA")]
public string CityReceiverUA { get; set; }
[XmlElement("CityReceiverRU")]
public string CityReceiverRU { get; set; }
[XmlElement("CitySenderSiteKey")]
public string CitySenderSiteKey { get; set; }
[XmlElement("CitySenderUA")]
public string CitySenderUA { get; set; }
[XmlElement("CitySenderRU")]
public string CitySenderRU { get; set; }
[XmlElement("DeliveryType")]
public string DeliveryType { get; set; }
[XmlElement("BackwardDeliveryNumber")]
public System.Guid BackwardDeliveryNumber { get; set; }
[XmlElement("RedeliveryCargoDescriptionMoney")]
public string RedeliveryCargoDescriptionMoney { get; set; }
[XmlElement("Failure")]
public Nullable<bool> Failure { get; set; }
[XmlElement("ReasonDescription")]
public string ReasonDescription { get; set; }
[XmlElement("GlobalMoneyExistDelivery")]
public Nullable<bool> GlobalMoneyExistDelivery { get; set; }
[XmlElement("GlobalMoneyLastTransactionStatus")]
public string GlobalMoneyLastTransactionStatus { get; set; }
[XmlElement("GlobalMoneyLastTransactionDate")]
public Nullable<System.DateTime> GlobalMoneyLastTransactionDate { get; set; }
[XmlElement("Sum")]
public Nullable<decimal> Sum { get; set; }
[XmlElement("DocumentWeight")]
public Nullable<decimal> DocumentWeight { get; set; }
[XmlElement("SumBeforeCheckWeight")]
public Nullable<decimal> SumBeforeCheckWeight { get; set; }
[XmlElement("isEWPaid")]
public Nullable<bool> isEWPaid { get; set; }
[XmlElement("isEWPaidCashLess")]
public Nullable<bool> isEWPaidCashLess { get; set; }
[XmlElement("ewPaidSumm")]
public Nullable<decimal> ewPaidSumm { get; set; }
[XmlElement("RedeliverySum")]
public Nullable<decimal> RedeliverySum { get; set; }
[XmlElement("OwnerDocumentType")]
public string OwnerDocumentType { get; set; }
public virtual DocumentStatus DocumentStatus { get; set; }
public virtual DocumentsTracking DocumentsTracking { get; set; }
}
}
What do I miss?
The property type is wrong. Modify your entity with the exact type. DocumentsTrackingChildDocuments isn't the same as DocumentsTrackingChildDocument.

Deserialize JSON response coming from SkyDrive to a Custom Class

I want to deserialize the JSON response coming from LiveConnectClient.GetAsync("me/skydrive/files") to a custom class to find out if a specific folder is there on the skydrive root. I got the json result from the skydrive and used json2csharp.com to get the class structure. Then i used Json.net's DeserializeObject method to deserialize the json to the class structure. But it throws an Exception during execution. I got the desired result without converting the json result. But i want to know what went wrong and how to convert it to my custom class. The code is given below
private async void btnFldrStruct_Click(object sender, RoutedEventArgs e)
{
LiveOperationResult opResult = await client.GetAsync("me/skydrive/files");
dynamic skyResult = opResult.Result;
var fileList = skyResult.data;
SkyDrive skydrive = JsonConvert.DeserializeObject<SkyDrive>(fileList);
...
}
Exception is thrown at
SkyDrive skydrive = JsonConvert.DeserializeObject<SkyDrive>(fileList);
The exception is
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
Message
The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject(string)'
has some invalid arguments
Stack Trace
at CallSite.Target(Closure , CallSite , Type , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
at SkyDriveTestApp.MainPage.<btnFldrStruct_Click>d__26.MoveNext()
The classes from json2csharp
public class From
{
public string name { get; set; }
public string id { get; set; }
}
public class SharedWith
{
public string access { get; set; }
}
public class Image
{
public int height { get; set; }
public int width { get; set; }
public string source { get; set; }
public string type { get; set; }
}
public class Datum
{
public string id { get; set; }
public From from { get; set; }
public string name { get; set; }
public string description { get; set; }
public string parent_id { get; set; }
public int size { get; set; }
public string upload_location { get; set; }
public int comments_count { get; set; }
public bool comments_enabled { get; set; }
public bool is_embeddable { get; set; }
public int count { get; set; }
public string link { get; set; }
public string type { get; set; }
public SharedWith shared_with { get; set; }
public string created_time { get; set; }
public string updated_time { get; set; }
public string client_updated_time { get; set; }
public int? tags_count { get; set; }
public bool? tags_enabled { get; set; }
public string picture { get; set; }
public string source { get; set; }
public List<Image> images { get; set; }
public string when_taken { get; set; }
public int? height { get; set; }
public int? width { get; set; }
public object location { get; set; }
public object camera_make { get; set; }
public object camera_model { get; set; }
public int? focal_ratio { get; set; }
public int? focal_length { get; set; }
public int? exposure_numerator { get; set; }
public int? exposure_denominator { get; set; }
}
public class SkyDrive
{
public List<Datum> data { get; set; }
}
can someone tell me what is wrong here and how to fix it. Thank you

Categories