How to make xmlroot a specific attribute in C# - c#

I recently have change my program to deserialize XML files. I created a class but it needs to be under certain attribute. I thought using XmlRootAttribute would work but I keep getting the error
InvalidOperationException: <DataFileSetup xmlns=''> was not expected.
Here is my code
[XmlRoot(ElementName = "DewesoftSetup")]
public class DewesoftDevices
{
[XmlElement(ElementName = "Devices")]
public List<DewesoftSetup> dewesoftSiriusSetups { get; set; }
};
public class DewesoftSetup
{
public double StartStoreTime;
public int SampleRate;
public int BlockSize;
public int IBRate;
public int AAFsr;
public int MaxSampling;
[XmlElement(ElementName = "Device")]
public List<DeviceType> deviceType { get; set; }
};
public class DeviceType
{
[XmlAttribute(AttributeName = "Type")]
public string deviceType;
[XmlElement(ElementName = "Slot")]
public List<Slot> slot { get; set; }
};
public class Slot
{
public string MeasuredValue { get; set; }
public string Range { get; set; }
public string LPFilter_Type { get; set; }
public string LPFilter_Hz { get; set; }
public string LPFilter_Order { get; set; }
public string HPFilter_Hz { get; set; }
public double AmplScale { get; set; }
public double AmplOffset { get; set; }
public string AmplShortInfo { get; set; }
public string NamePrefix { get; set; }
[XmlElement(ElementName = "OutputChannel")]
public OutputChannel outputChannel;
[XmlElement(ElementName = "AmplifierChainInfo/AmplifierInfo")]
public AmplifierInfo ampInfo;
}
public class DewesoftCard
{
public static string xmlFileName = #"C:\Dewesoft\SetupFile.xml";
public double startStoreTime;
public int sampleRate;
public int blockSize;
public int ibRate;
public int aafSR;
public int maxSampling;
public int startZoomTime;
public int endZoomTime;
};
public class OutputChannel
{
public string Name { get; set; }
public string Description { get; set; }
public string Unit { get; set; }
public int userScaleMin { get; set; }
public int userScaleMax { get; set; }
public int defaultComplexPresent { get; set; }
public string Used { get; set; }
public string Index { get; set; }
public int DataType { get; set; }
public double Scale { get; set; }
public double Offset { get; set; }
public double RangeMax { get; set; }
public double RangeMin { get; set; }
public int BitsLog { get; set; }
public int SigBitCount { get; set; }
public int BitsForMinMax { get; set; }
public int BitCount { get; set; }
public int ExportOrder { get; set; }
public string MeasuredQuantity { get; set; }
public int AmplifierScaleMin { get; set; }
public int AmplifierScaleMax { get; set; }
};
public class AmplifierInfo
{
public string Name { get; set; }
public string Type { get; set; }
public string SerialNr { get; set; }
public string Revision { get; set; }
public string Firmware { get; set; }
public string CalDate { get; set; }
public string Range { get; set; }
public string LP_filter { get; set; }
public string LP_filter_type { get; set; }
public string LP_filter_order { get; set; }
public string HP_filter { get; set; }
};
public static void readXML()
{
XmlReader reader = XmlReader.Create(DewesoftCard.xmlFileName);
reader.ReadToFollowing("DewesoftSetup");
XmlSerializer serializer = new XmlSerializer(typeof(DewesoftDevices));
DewesoftDevices setup = (DewesoftDevices)serializer.Deserialize(reader);
}
<?xml version="1.0" encoding="UTF-8"?>
<DataFileSetup>
<System Name="Local">
<SysInfo>
<Software>
<VersionCreated>X3 SP5 (RELEASE-181228) (64-bit)</VersionCreated>
<VersionModifed>X3 SP5 (RELEASE-181228) (64-bit)</VersionModifed>
<License_Type>Professional</License_Type>
</Software>
</SysInfo>
<DewesoftSetup>
<Devices>
<StartStoreTime>43874.6969328704</StartStoreTime>
<SampleRate>50000</SampleRate>
<BlockSize>1000</BlockSize>
<IBRate>10</IBRate>
<AAFsr>21000</AAFsr>
<MaxSampling>200000</MaxSampling>
<Device Type="AI">
<Slot Index="0">
<MeasuredValue>VOLTAGE</MeasuredValue>
<Range>10 V</Range>
<LPFilter_Type>BU</LPFilter_Type>
<LPFilter_Hz>10000</LPFilter_Hz>
<LPFilter_Order>2</LPFilter_Order>
<HPFilter_Hz>1</HPFilter_Hz>
<OutMathChEnabled>8;1;0;0;0;0;0;0;0</OutMathChEnabled>
<OutputChannel>
<DisplayColor>#FFFF00</DisplayColor>
<Name>ACC-1X</Name>
<Description>Dome</Description>
<DefaultUnit>False</DefaultUnit>
<Unit>g</Unit>
<DefaultComplexPresent>1</DefaultComplexPresent>
<Used>True</Used>
<Index>AI;0</Index>
<DataType>4</DataType>
<Scale>200</Scale>
<RangeMax>2000</RangeMax>
<RangeMin>-2000</RangeMin>
<BitsLog>24</BitsLog>
<SigBitCount>19</SigBitCount>
<BitsForMinMax>24</BitsForMinMax>
<BitCount>24</BitCount>
<SIUnit>
<Label>g</Label>
<PhysicalQuantity>ACCELERATION</PhysicalQuantity>
<MetricPos>1</MetricPos>
<ImperialPos>1</ImperialPos>
<CustomPos>1</CustomPos>
<EditEnable>False</EditEnable>
<Scale>0.101972</Scale>
</SIUnit>
<MeasuredQuantity>ACCELERATION</MeasuredQuantity>
<OnlineInfo>
<IBStream Level="0"></IBStream>
<IBStream Level="1"></IBStream>
<IBStream Level="2"></IBStream>
<IBStream Level="3"></IBStream>
<IBStream Level="4"></IBStream>
<IBStream Level="5"></IBStream>
</OnlineInfo>
<AmplifierScaleMin>-10</AmplifierScaleMin>
<AmplifierScaleMax>10</AmplifierScaleMax>
</OutputChannel>
<AmplifierChainInfo>
<AmplifierInfo Index="0" Type="DEWEUSB_AMPLIFIER">
<Name>SIRIUS-HD-ACC</Name>
<SerialNr>D013C47522</SerialNr>
<Revision>1.3.0.0</Revision>
<Firmware>1.10</Firmware>
<CalDate>09.01.2020</CalDate>
<Measurement>Voltage</Measurement>
<Range>10 V</Range>
<LP_filter>10 kHz* (HW: 100 kHz)</LP_filter>
<LP_filter_type>Butterworth*</LP_filter_type>
<LP_filter_order>2nd*</LP_filter_order>
<HP_filter>AC 1 Hz (SW: 0.1 Hz)</HP_filter>
</AmplifierInfo>
</AmplifierChainInfo>
</Slot>
</Device>
</Devices>
</DewesoftSetup>
</System>
</DataFileSetup>
There are multiple "Device" attributes but I need the one under DewesoftSetup.
EDIT i have added more of the xml document. I am trying to add the device type to a list and the slot to list since there will be multiples of them.

Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
readXML();
}
public static void readXML()
{
XmlReader reader = XmlReader.Create(FILENAME);
reader.ReadToFollowing("DewesoftSetup");
XmlSerializer serializer = new XmlSerializer(typeof(DewesoftDevices));
DewesoftDevices setup = (DewesoftDevices)serializer.Deserialize(reader);
}
}
[XmlRoot(ElementName = "DewesoftSetup")]
public class DewesoftDevices
{
[XmlElement(ElementName = "Devices")]
public List<Devices> devices { get; set; }
}
public class Devices
{
public string StartStoreTime;
public int SampleRate;
public int IBRate;
public int AAFsr;
public int MaxSampling;
[XmlElement(ElementName = "Device")]
public List<DeviceType> deviceType { get; set; }
}
public class DeviceType
{
[XmlAttribute(AttributeName = "Type")]
public string deviceType;
[XmlElement(ElementName = "Slot")]
public List<Slot> slot { get; set; }
}
public class Slot
{
public string Range { get; set; }
public OutputChannel OutputChannel { get; set; }
[XmlArray("AmplifierChainInfo")]
[XmlArrayItem("AmplifierInfo")]
public List<AmplifierInfo> AmplifierInfo { get; set; }
}
public class OutputChannel
{
public string Name { get; set; }
}
public class AmplifierInfo
{
public string Name { get; set; }
}
}

Related

Consuming web API into Blazor

I'm trying to consume a web API into Blazor but am struggling to extract certain information from the API
using System.Text.Json;
namespace CA3.Song
{
public class SongService : ISongService
{
private readonly HttpClient _httpClient;
const string _baseUrl = "https://genius-song-lyrics1.p.rapidapi.com/";
const string _songEndpoint = "songs/chart?time_period=day&chart_genre=all&per_page=10&page=1";
const string _host = "genius-song-lyrics1.p.rapidapi.com";
const string _key = "{key}";
public SongService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<List<SongItem>> GetSong()
{
Configure();
var response = await _httpClient.GetAsync(_songEndpoint);
var response_outcome = response.EnsureSuccessStatusCode;
using var stream = await response.Content.ReadAsStreamAsync();
var dto = await JsonSerializer.DeserializeAsync<SongDto>(stream);
return dto.response.chart_items.Select(n => new SongItem { Artist = n.item.primary_artist, Title = n.item.primary_title, ReleaseDate = n.primary_release_date }).ToList().T ;
}
private void Configure()
{
_httpClient.BaseAddress = new Uri(_baseUrl);
_httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Host", _host);
_httpClient.DefaultRequestHeaders.Add("X-Rapid-Key", _key);
}
}
}
The issue is on the return statement using LINQ.
namespace CA3.Song
{
public class SongDto
{
public Meta meta { get; set; }
public Response response { get; set; }
}
public class Meta
{
public int status { get; set; }
}
public class Response
{
public Chart_Items[] chart_items { get; set; }
public int next_page { get; set; }
}
public class Chart_Items
{
public string _type { get; set; }
public string type { get; set; }
public Item item { get; set; }
}
public class Item
{
public string _type { get; set; }
public int annotation_count { get; set; }
public string api_path { get; set; }
public string artist_names { get; set; }
public string full_title { get; set; }
public string header_image_thumbnail_url { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public bool instrumental { get; set; }
public int lyrics_owner_id { get; set; }
public string lyrics_state { get; set; }
public int lyrics_updated_at { get; set; }
public string path { get; set; }
public int pyongs_count { get; set; }
public string relationships_index_url { get; set; }
public Release_Date_Components release_date_components { get; set; }
public string release_date_for_display { get; set; }
public string song_art_image_thumbnail_url { get; set; }
public string song_art_image_url { get; set; }
public Stats stats { get; set; }
public string title { get; set; }
public string title_with_featured { get; set; }
public int updated_by_human_at { get; set; }
public string url { get; set; }
public Featured_Artists[] featured_artists { get; set; }
public Primary_Artist primary_artist { get; set; }
}
public class Release_Date_Components
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
public class Stats
{
public int unreviewed_annotations { get; set; }
public int concurrents { get; set; }
public bool hot { get; set; }
public int pageviews { get; set; }
}
public class Primary_Artist
{
public string _type { get; set; }
public string api_path { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public string index_character { get; set; }
public bool is_meme_verified { get; set; }
public bool is_verified { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string url { get; set; }
public int iq { get; set; }
}
public class Featured_Artists
{
public string _type { get; set; }
public string api_path { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public string index_character { get; set; }
public bool is_meme_verified { get; set; }
public bool is_verified { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string url { get; set; }
public int iq { get; set; }
}
}
Above is the JSON file and I'm trying to extract the artist name, song title and release date from Item but it isn't in a list so I'm trying to find a way to extract this info using LINQ. Any help would be greatly appreciated !
I think you misinterpreted the declaration of the JSON. They are stored in an array Chart_Items[] chart_items thus you may use linq.
There are many ways to do this, I took advantage of named tuples in modern C# paired with linq.
Response r = new Response();//some resonse from api
var results = r.chart_items.Select(i => (i.item.artist_names, i.item.title, i.item.release_date_components)).ToList();
foreach(var result in results)
{
string artist_names = result.artist_names;
string title = result.title;
Release_Date_Components release_date_components = result.release_date_components;
}

Error deserializing XML file into C# class of objects

I have this xml file:
<?xml version="1.0" encoding="UTF-8"?>
<pippo:Response xmlns:pippo="http://pippoonboarding.eu">
<pippo:Header>
<pippo:FileId>123</pippo:FileId>
<pippo:SenderId>1234</pippo:SenderId>
<pippo:ProcessingDate>20210630</pippo:ProcessingDate>
<pippo:ProcessingTime>1130</pippo:ProcessingTime>
<pippo:ResponseCode>OK</pippo:ResponseCode>
</pippo:Header>
<pippo:CompanyResponse>
<pippo:SellerId>1234</pippo:SellerId>
<pippo:SellerContractCode />
<pippo:VATNumber>123456</pippo:VATNumber>
<pippo:ResponseCode>KO</pippo:ResponseCode>
<pippo:PippoCompanyCode />
<pippo:ResponseDetails>
<pippo:Entity>ciaone</pippo:Entity>
<pippo:ProgressiveNumber>1</pippo:ProgressiveNumber>
<pippo:PippoShopCode />
<pippo:TerminalId />
<pippo:FieldName />
<pippo:ErrorType>DDD</pippo:ErrorType>
<pippo:ErrorCode>1234</pippo:ErrorCode>
<pippo:ErrorDescription>test</pippo:ErrorDescription>
</pippo:ResponseDetails>
</pippo:CompanyResponse>
</pippo:Response>
and I want to deserialize into my class:
public class XmlDeserializer
{
[Serializable, XmlRoot("pippo:Response xmlns:pippo=\"http://pippoonboarding.eu\"")]
public class Root
{
public string Response { get; set; }
//[XmlElement(ElementName = "Header")]
public Header Header { get; set; }
public CompanyResponse CompanyResponse { get; set; }
}
public class Header
{
public string FileId { get; set; }
public string SenderId { get; set; }
public string ProcessingDate { get; set; }
public string ProcessingTime { get; set; }
public string ResponseCode { get; set; }
}
public class CompanyResponse
{
public string SellerId { get; set; }
public int SellerContractCode { get; set; }
public int VATNumber { get; set; }
public int ResponseCode { get; set; }
public int PippoCompanyCode { get; set; }
public ResponseDetails ResponseDetails { get; set; }
}
public class ResponseDetails
{
public string Entity { get; set; }
public string ProgressiveNumber { get; set; }
public string PippoShopCode { get; set; }
public string TerminalId { get; set; }
public string FieldName { get; set; }
public string ErrorType { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
}
but I receive this error:
There is an error in XML document (2, 2).
<Response xmlns='http://pippoonboarding.eu'> was not expected.
What does the error mean? What should I do?
Following code works. Had to change a few integers to strings in class definitions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication2
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlDeserializer response = new XmlDeserializer(FILENAME);
}
}
public class XmlDeserializer
{
public XmlDeserializer(string filename)
{
XmlReader reader = XmlReader.Create(filename);
XmlSerializer serializer = new XmlSerializer(typeof(Root));
Root response = (Root)serializer.Deserialize(reader);
}
[XmlRoot(ElementName = "Response", Namespace = "http://pippoonboarding.eu")]
public class Root
{
public string Response { get; set; }
//[XmlElement(ElementName = "Header")]
public Header Header { get; set; }
public CompanyResponse CompanyResponse { get; set; }
}
public class Header
{
public string FileId { get; set; }
public string SenderId { get; set; }
public string ProcessingDate { get; set; }
public string ProcessingTime { get; set; }
public string ResponseCode { get; set; }
}
public class CompanyResponse
{
public string SellerId { get; set; }
public string SellerContractCode { get; set; }
public int VATNumber { get; set; }
public string ResponseCode { get; set; }
public string PippoCompanyCode { get; set; }
public ResponseDetails ResponseDetails { get; set; }
}
public class ResponseDetails
{
public string Entity { get; set; }
public string ProgressiveNumber { get; set; }
public string PippoShopCode { get; set; }
public string TerminalId { get; set; }
public string FieldName { get; set; }
public string ErrorType { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
}
}

Xml deserialization returns empty array even though POCO has right xml attributes generated from xsd2code++ tool

I am using XSD2Code++ 2019 tool for visual studio to generate POCOs from aset of 5 xsds. I have added the POCO class below. I see that it has the right xml decorators for it to serialize properly. But I really fail to understand or figure out why the 3rd level object in the returned deserialized data is always empty and not typecasted to the correct type.
I have tried changing attributes to xmlArray and xmlArrayElement too but none of that worked.
POCO class-
https://gist.github.com/nimisha84/b86a4bb2bf37aea6ec351a9f6e331bed
Sample xml response which has null values after deserialization using c# code-
<?xml version="1.0" encoding="UTF-8"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2019-07-05T14:29:08.603-07:00">
<QueryResponse startPosition="1" maxResults="1" totalCount="1">
<Invoice domain="QBO" sparse="false">
<Id>8633</Id>
<SyncToken>14</SyncToken>
<MetaData>
<CreateTime>2019-01-09T11:32:12-08:00</CreateTime>
<LastUpdatedTime>2019-06-05T12:49:40-07:00</LastUpdatedTime>
</MetaData>
<CustomField>
<DefinitionId>1</DefinitionId>
<Name>CustomPO</Name>
<Type>StringType</Type>
<StringValue>Gold</StringValue>
</CustomField>
<DocNumber>2830</DocNumber>
<TxnDate>2019-01-09</TxnDate>
<CurrencyRef name="United States Dollar">USD</CurrencyRef>
<ExchangeRate>1</ExchangeRate>
<PrivateNote>Voided - Voided</PrivateNote>
<Line>
<Id>1</Id>
<LineNum>1</LineNum>
<Description>Description</Description>
<Amount>0</Amount>
<DetailType>SalesItemLineDetail</DetailType>
<SalesItemLineDetail>
<ItemRef name="Name27140">815</ItemRef>
<Qty>0</Qty>
<TaxCodeRef>NON</TaxCodeRef>
</SalesItemLineDetail>
</Line>
<Line>
<Amount>0</Amount>
<DetailType>SubTotalLineDetail</DetailType>
<SubTotalLineDetail />
</Line>
<TxnTaxDetail>
<TotalTax>0</TotalTax>
</TxnTaxDetail>
<CustomerRef name="a4">2561</CustomerRef>
<DueDate>2019-01-09</DueDate>
<TotalAmt>0</TotalAmt>
<HomeTotalAmt>0</HomeTotalAmt>
<ApplyTaxAfterDiscount>false</ApplyTaxAfterDiscount>
<PrintStatus>NeedToPrint</PrintStatus>
<EmailStatus>NotSet</EmailStatus>
<Balance>0</Balance>
<Deposit>0</Deposit>
<AllowIPNPayment>false</AllowIPNPayment>
<AllowOnlinePayment>false</AllowOnlinePayment>
<AllowOnlineCreditCardPayment>false</AllowOnlineCreditCardPayment>
<AllowOnlineACHPayment>false</AllowOnlineACHPayment>
</Invoice>
</QueryResponse>
</IntuitResponse>
Code to deserialize-
string responseText = apiResponse.ReadToEnd();
var responseSerializer = new XmlObjectSerializer();
IntuitResponse restResponse =
(IntuitResponse)this.responseSerializer.Deserialize<IntuitResponse>(responseText);
res=restResponse.Items[0] as QueryResponse;
here QueryResponse is not having Invoice(of type IntuitEntity) object returned. Instead empty value is returned. See screenshot.
https://imgur.com/a/5yF6Khb
I really need help to figure out why the 3rd level property is returned as empty.
I tested code below and it works. I manually generated the classes which produces simpler results than using tools.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string responseText = File.ReadAllText(FILENAME);
StringReader reader = new StringReader(responseText);
XmlReader xReader = XmlReader.Create(reader);
XmlSerializer serializer = new XmlSerializer(typeof(IntuitResponse));
IntuitResponse response = (IntuitResponse)serializer.Deserialize(xReader);
}
}
[XmlRoot(ElementName = "IntuitResponse", Namespace = "http://schema.intuit.com/finance/v3")]
public class IntuitResponse
{
[XmlAttribute("time")]
public DateTime time { get; set; }
[XmlElement(ElementName = "QueryResponse", Namespace = "http://schema.intuit.com/finance/v3")]
public QueryResponse response { get; set; }
}
public class QueryResponse
{
[XmlAttribute("startPosition")]
public int startPosition { get; set; }
[XmlAttribute("maxResults")]
public int maxResults { get; set; }
[XmlAttribute("totalCount")]
public int totalCount { get; set; }
[XmlElement(ElementName = "Invoice", Namespace = "http://schema.intuit.com/finance/v3")]
public Invoice invoice { get; set; }
}
public class Invoice
{
[XmlAttribute("domain")]
public string domain { get; set; }
[XmlAttribute("sparse")]
public Boolean sparse { get; set; }
public int Id { get; set; }
public int SyncToken { get; set; }
[XmlElement(ElementName = "MetaData", Namespace = "http://schema.intuit.com/finance/v3")]
public MetaData metaData { get; set; }
[XmlElement(ElementName = "CustomField", Namespace = "http://schema.intuit.com/finance/v3")]
public CustomField customField { get; set; }
public int DocNumber { get; set; }
public DateTime TxnDate { get; set; }
[XmlElement(ElementName = "CurrencyRef", Namespace = "http://schema.intuit.com/finance/v3")]
public CurrencyRef currencyRef { get; set; }
public int ExchangeRate { get; set; }
public string PrivateNote { get; set; }
[XmlElement(ElementName = "Line", Namespace = "http://schema.intuit.com/finance/v3")]
public List<Line> line { get; set; }
[XmlElement(ElementName = "TxnTaxDetail", Namespace = "http://schema.intuit.com/finance/v3")]
public TxnTaxDetail txnTaxDetail { get; set; }
[XmlElement(ElementName = "CustomerRef", Namespace = "http://schema.intuit.com/finance/v3")]
public CustomerRef CustomerRef { get; set; }
public DateTime DueDate { get; set; }
public int TotalAmt { get; set; }
public int HomeTotalAmt { get; set; }
public Boolean ApplyTaxAfterDiscount { get; set; }
public string PrintStatus { get; set; }
public string EmailStatus { get; set; }
public int Balance { get; set; }
public int Deposit { get; set; }
public Boolean AllowIPNPayment { get; set; }
public Boolean AllowOnlinePayment { get; set; }
public Boolean AllowOnlineCreditCardPayment { get; set; }
public Boolean AllowOnlineACHPayment { get; set; }
}
public class MetaData
{
public DateTime CreateTime { get; set; }
public DateTime LastUpdatedTime { get; set; }
}
public class CustomField
{
public int DefinitionId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string StringValue { get; set; }
}
public class CurrencyRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class Line
{
public int Id { get; set; }
public int LineNum { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public string DetailType { get; set; }
[XmlElement(ElementName = "SalesItemLineDetail", Namespace = "http://schema.intuit.com/finance/v3")]
public SalesItemLineDetail salesItemLineDetail { get; set; }
}
public class CustomerRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class SalesItemLineDetail
{
[XmlElement(ElementName = "ItemRef", Namespace = "http://schema.intuit.com/finance/v3")]
public ItemRef itemRef { get; set; }
public int Qty { get; set; }
public string TaxCodeRef { get; set; }
}
public class ItemRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class TxnTaxDetail
{
public int TotalTax { get; set; }
}
}

Deserialize JSON using NewtonSoft

I have created classes needed by help of a website, but can't deserialize.
public class Brand
{
public string name { get; set; }
}
public class Link
{
public string href { get; set; }
}
public class Price
{
public double current { get; set; }
}
public class RootObject
{
public Brand brand { get; set; }
public string href { get; set; }
public List<Link> links { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Price price { get; set; }
public string productId { get; set; }
}
How I am trying in C#
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952"
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<RootObject>(result);
foreach (Brand p in jsonresult)
{
Debug.WriteLine(p);
}
I know I'm doing something wrong, but can anyone help me to correctly get the elements from the classes above only?
There are few mistakes in the code you've provided:
The json which is received from endpoint, is a json array.
So, instead of deserialzing as RootObject you should deserialize as List<RootObject>.
While iterating through jsonresult you should use RootObject instead of Brand
So here is the complete solution:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Diagnostics;
public class Brand
{
public string name { get; set; }
}
public class Link
{
public string href { get; set; }
}
public class Price
{
public double current { get; set; }
}
public class RootObject
{
public Brand brand { get; set; }
public string href { get; set; }
public List<Link> links { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Price price { get; set; }
public string productId { get; set; }
}
public class Program
{
public static void Main()
{
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<List<RootObject>>(result);
foreach (RootObject p in jsonresult)
{
Debug.WriteLine(p.brand.name);
foreach (Link link in p.links){
Debug.WriteLine(link.href);
}
foreach (string mpn in p.mpns){
Debug.WriteLine(mpn);
}
}
}
}
And here is the online version just in case it's needed.
Finally, I did it.kindly change your Model. The model should match your JSON data. You can check the complete solution
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
namespace Jsondemo
{
public class Brand
{
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string support { get; set; }
public string url { get; set; }
}
public class Path
{
public string id { get; set; }
public string name { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public List<Path> path { get; set; }
}
public class Installment
{
public int months { get; set; }
public int monthlySum { get; set; }
public double totalAmount { get; set; }
public double annualInterestRate { get; set; }
public double interest { get; set; }
public double fee { get; set; }
}
public class UiLabels
{
public string text { get; set; }
public string price { get; set; }
public string time { get; set; }
public List<string> tooltip { get; set; }
}
public class Installment2
{
public int months { get; set; }
public string monthlySum { get; set; }
public double totalAmount { get; set; }
public double annualInterestRate { get; set; }
public double interest { get; set; }
public double fee { get; set; }
}
public class UiLabels2
{
public string text { get; set; }
public string price { get; set; }
public string time { get; set; }
public List<string> tooltip { get; set; }
}
public class CompanyFinancing
{
public List<Installment2> installments { get; set; }
public UiLabels2 uiLabels { get; set; }
}
public class Financing
{
public List<Installment> installments { get; set; }
public string type { get; set; }
public double price { get; set; }
public UiLabels uiLabels { get; set; }
public CompanyFinancing companyFinancing { get; set; }
}
public class Image
{
public string __invalid_name__45 { get; set; }
public string __invalid_name__90 { get; set; }
public string __invalid_name__300 { get; set; }
public string __invalid_name__500 { get; set; }
public string __invalid_name__960 { get; set; }
public string orig { get; set; }
}
public class Link
{
public string name { get; set; }
public string type { get; set; }
public string href { get; set; }
}
public class Package
{
public int width { get; set; }
public int height { get; set; }
public int depth { get; set; }
public int volume { get; set; }
public int weight { get; set; }
}
public class Price
{
public double current { get; set; }
public double currentTaxless { get; set; }
public string currentFormatted { get; set; }
public double original { get; set; }
public double originalTaxless { get; set; }
public string originalFormatted { get; set; }
public object discountAmount { get; set; }
public object discountPercentage { get; set; }
public int taxRate { get; set; }
public object discount { get; set; }
public object deposit { get; set; }
public object unit { get; set; }
}
public class Rating
{
public int reviewCount { get; set; }
public int averageOverallRating { get; set; }
public int recommendedCount { get; set; }
}
public class Relations
{
public List<object> recommended { get; set; }
public List<object> newer { get; set; }
public List<object> older { get; set; }
public List<object> bundles { get; set; }
}
public class Restrictions
{
public bool isRestricted { get; set; }
public List<object> pickupAllowed { get; set; }
public List<object> postalCodeAllowed { get; set; }
public string description { get; set; }
public string descriptionShort { get; set; }
}
public class ShipmentPrice
{
public int id { get; set; }
public string name { get; set; }
public double price { get; set; }
public bool pickup { get; set; }
}
public class Js
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Pak
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Vendor
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Warehouses
{
public Js js { get; set; }
public Pak pak { get; set; }
public Vendor vendor { get; set; }
}
public class Web
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
public Warehouses warehouses { get; set; }
public string ranking { get; set; }
}
public class Js2
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class JsKioski
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Oul
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pir
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Rai
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu1
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu2
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu3
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu4
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Stores
{
public Js2 js { get; set; }
public JsKioski js_kioski { get; set; }
public Oul oul { get; set; }
public Pir pir { get; set; }
public Rai rai { get; set; }
public Pu1 pu1 { get; set; }
public Pu2 pu2 { get; set; }
public Pu3 pu3 { get; set; }
public Pu4 pu4 { get; set; }
}
public class Stocks
{
public Web web { get; set; }
public Stores stores { get; set; }
}
public class Availability
{
public string _id { get; set; }
public int pid { get; set; }
public object overrideText { get; set; }
public bool isElectronic { get; set; }
public bool isVirtual { get; set; }
public bool isInStoresOnly { get; set; }
public bool isReleased { get; set; }
public bool isShippingAllowed { get; set; }
public bool isPickupAllowed { get; set; }
public bool isStockVisible { get; set; }
public bool isPurchasable { get; set; }
public bool isSoldOut { get; set; }
public bool isEOL { get; set; }
public bool isFastDeliveryAvailable { get; set; }
public bool isStoreOrderAllowed { get; set; }
public bool hasStock { get; set; }
public Stocks stocks { get; set; }
public List<object> tags { get; set; }
public DateTime updatedAt { get; set; }
public DateTime verifiedAt { get; set; }
public int updateCount { get; set; }
public DateTime updateStartTime { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public bool active { get; set; }
public int ageLimit { get; set; }
public Brand brand { get; set; }
public List<string> bulletPoints { get; set; }
public List<object> bundleProducts { get; set; }
public List<object> campaigns { get; set; }
public List<string> categories { get; set; }
public Category category { get; set; }
public DateTime createdAt { get; set; }
public List<object> demoLocations { get; set; }
public string description { get; set; }
public string descriptionShort { get; set; }
public List<string> eans { get; set; }
public bool electronic { get; set; }
public Financing financing { get; set; }
public string freeShipmentFor { get; set; }
public bool hidePriceEstimate { get; set; }
public string href { get; set; }
public List<Image> images { get; set; }
public List<Link> links { get; set; }
public object maxAmountPerOrder { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Package package { get; set; }
public int pid { get; set; }
public Price price { get; set; }
public string productId { get; set; }
public Rating rating { get; set; }
public Relations relations { get; set; }
public DateTime releasedAt { get; set; }
public Restrictions restrictions { get; set; }
public List<string> ribbons { get; set; }
public List<ShipmentPrice> shipmentPrices { get; set; }
public List<object> shopAreas { get; set; }
public bool vak { get; set; }
public int visible { get; set; }
public string warranty { get; set; }
public DateTime updatedAt { get; set; }
public DateTime verifiedAt { get; set; }
public int updateCount { get; set; }
public DateTime updateStartTime { get; set; }
public Availability availability { get; set; }
}
class Program
{
static void Main(string[] args)
{
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<List<RootObject>>(result);
foreach (RootObject p in jsonresult)
{
foreach (var item in p.links)
{
Debug.WriteLine(item.href);
}
}
Console.WriteLine("Hello World!");
}
}
}
You can use https://quicktype.io to generate c# code with entities from JSON.
i have created the c# classes for your json request.
https://app.quicktype.io?share=KNyJfG7rGBZH96H6yNXe

XML File convert to C# object

I have to read this XML File in a C# Object. That i have these information in an Object. Not all tags are important!
These would be the important information i need in the Object:
- Alignment with the staStart Property
- CoordGoem with Line Spiral and Curve inside and of thesse are only the properties important
XML File
<Alignments name="">
<Alignment name="AL-voor omvorming landxml" length="6550.000000000015" staStart="30000." desc="">
<CoordGeom>
<Line dir="0." length="100.">
<Start>175.282796686952 -1708.474133524573</Start>
<End>175.282796686952 -1608.474133524573</End>
</Line>
<Spiral length="100." radiusEnd="500." radiusStart="INF" rot="cw" spiType="clothoid" theta="5.729577951308" totalY="3.330953138396" totalX="99.900046285614" tanLong="66.701620764677" tanShort="33.365112106501">
<Start>175.282796686952 -1608.474133524573</Start>
<PI>175.282796686952 -1541.772512759896</PI>
<End>171.951843548555 -1508.574087238959</End>
</Spiral>
<Curve rot="cw" chord="99.833416646828" crvType="arc" delta="11.459155902616" dirEnd="342.811266146075" dirStart="354.270422048692" external="2.510459200228" length="100." midOrd="2.497917360987" radius="500." tangent="50.167336042725">
<Start>171.951843548555 -1508.574087238959</Start>
<Center>-325.550239090457 -1558.490795562373</Center>
<End>152.118005472345 -1410.730692231703</End>
<PI>166.94346698734 -1458.657378915545</PI>
</Curve>
<Spiral length="100." radiusEnd="INF" radiusStart="500." rot="cw" spiType="clothoid" theta="5.729577951308" totalY="3.330953138396" totalX="99.900046285614" tanLong="66.701620764677" tanShort="33.365112106501">
<Start>152.118005472345 -1410.730692231703</Start>
<PI>142.257940647353 -1378.855783172596</PI>
<End>116.283106059873 -1317.419522049479</End>
</Spiral>
Object
public class LandXMLAlignments
{
public long staStart { get; set; }
[XmlArray("CoordGeom")]
public List<LandXMLAlignmentsCoordGeom> CoordGeoms { get; set; }
}
public class LandXMLAlignmentsCoordGeom
{
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomLines { get; set; }
public List<LandXMLAlignmentsCoordGeomSpiral> CoordGeomSpiral { get; set; }
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomCurve { get; set; }
}
[System.Xml.Serialization.XmlType("Line", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomLine
{
public int length { get; set; }
public int position { get; set; }
}
[System.Xml.Serialization.XmlType("Spiral", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomSpiral
{
public int position { get; set; }
public int length { get; set; }
public string radiusStart { get; set; }
public string radiusEnd { get; set; }
public string rot { get; set; }
public string spiType { get; set; }
}
[System.Xml.Serialization.XmlType("Curve", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomCurve
{
public int position { get; set; }
public int length { get; set; }
public int radiusStart { get; set; }
public string rot { get; set; }
}
I would have drawn this object from it but i don't now how i actually read the xml file in this Object.
Assuming your classes are ok you could just create a helper class to perfom transformations from XML to a POCO object like this:
public static class XmlHelper
{
public static T ParseXmlFile<T>(string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StreamReader(filePath))
{
T configuration = (T)serializer.Deserialize(reader);
return configuration;
}
}
}
And use it like this:
var alignments = XmlHelper.ParseXmlFile<LandXMLAlignments>(YourXMLPath);
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication51
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Alignments));
Alignments alignments = (Alignments)serializer.Deserialize(reader);
}
}
public class Alignments
{
[XmlElement("Alignment")]
public Alignment alignment { get; set; }
}
public class Alignment
{
public long staStart { get; set; }
[XmlElement("CoordGeom")]
public List<LandXMLAlignmentsCoordGeom> CoordGeoms { get; set; }
}
public class LandXMLAlignmentsCoordGeom
{
[XmlElement("Line")]
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomLines { get; set; }
[XmlElement("Spiral")]
public List<LandXMLAlignmentsCoordGeomSpiral> CoordGeomSpiral { get; set; }
[XmlElement("Curve")]
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomCurve { get; set; }
}
[System.Xml.Serialization.XmlType("Line", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomLine
{
public int length { get; set; }
public int position { get; set; }
}
[System.Xml.Serialization.XmlType("Spiral", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomSpiral
{
public int position { get; set; }
public int length { get; set; }
public string radiusStart { get; set; }
public string radiusEnd { get; set; }
public string rot { get; set; }
public string spiType { get; set; }
}
[System.Xml.Serialization.XmlType("Curve", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomCurve
{
public int position { get; set; }
public int length { get; set; }
public int radiusStart { get; set; }
public string rot { get; set; }
}
}
If you are using Visual studio, then do the following:
Copy XML
Select Edit Menu,
Paste Special, Paste XML as Classes.
Reference

Categories