Can not deserialize Xml getting from api - c#

I am using World Weather Online API to get the weathers of specific location. My problem is while I am trying to deserialize XML output coming from API Response stream, I am getting error with: There is a problem with XML document (1,1).
Uri apiURL = new Uri(#"http://api.worldweatheronline.com/free/v1/weather.ashx?q=Dhaka&format=xml&num_of_days=1&date=today&key=jzb88bpzb5yvaegukmq97mee");
Stream result = RequestHandler.Process(apiURL.ToString());
XmlSerializer des = new XmlSerializer(typeof(LocalWeather));
StreamReader tr = new StreamReader(result);
Object obj = des.Deserialize(tr);
LocalWeather data = (LocalWeather)obj;
Sample XML file from Web API:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<request>
<type>City</type>
<query>Dhaka, Bangladesh</query>
</request>
<current_condition>
<observation_time>01:57 PM</observation_time>
<temp_C>33</temp_C>
<temp_F>91</temp_F>
<weatherCode>113</weatherCode>
<weatherIconUrl>
<![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[Clear ]]>
</weatherDesc>
<windspeedMiles>2</windspeedMiles>
<windspeedKmph>4</windspeedKmph>
<winddirDegree>77</winddirDegree>
<winddir16Point>ENE</winddir16Point>
<precipMM>0.0</precipMM>
<humidity>76</humidity>
<visibility>10</visibility>
<pressure>1006</pressure>
<cloudcover>2</cloudcover>
</current_condition>
<weather>
<date>2013-10-11</date>
<tempMaxC>36</tempMaxC>
<tempMaxF>97</tempMaxF>
<tempMinC>25</tempMinC>
<tempMinF>77</tempMinF>
<windspeedMiles>5</windspeedMiles>
<windspeedKmph>8</windspeedKmph>
<winddirection>ENE</winddirection>
<winddir16Point>ENE</winddir16Point>
<winddirDegree>65</winddirDegree>
<weatherCode>113</weatherCode>
<weatherIconUrl>
<![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[Sunny]]>
</weatherDesc>
<precipMM>0.0</precipMM>
</weather>
</data>
LocalWeather class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace APISample
{
public class LocalWeather
{
public Data data { get; set; }
}
public class Data
{
public List<Current_Condition> current_Condition { get; set; }
public List<Request> request { get; set; }
public List<Weather> weather { get; set; }
}
public class Current_Condition
{
public DateTime observation_time { get; set; }
public DateTime localObsDateTime { get; set; }
public int temp_C { get; set; }
public int windspeedMiles { get; set; }
public int windspeedKmph { get; set; }
public int winddirDegree { get; set; }
public string winddir16Point { get; set; }
public string weatherCode { get; set; }
public List<WeatherDesc> weatherDesc { get; set; }
public List<WeatherIconUrl> weatherIconUrl { get; set; }
public float precipMM { get; set; }
public float humidity { get; set; }
public int visibility { get; set; }
public int pressure { get; set; }
public int cloudcover { get; set; }
}
public class Request
{
public string query { get; set; }
public string type { get; set; }
}
public class Weather
{
public DateTime date { get; set; }
public int tempMaxC { get; set; }
public int tempMaxF { get; set; }
public int tempMinC { get; set; }
public int tempMinF { get; set; }
public int windspeedMiles { get; set; }
public int windspeedKmph { get; set; }
public int winddirDegree { get; set; }
public string winddir16Point { get; set; }
public string weatherCode { get; set; }
public List<WeatherDesc> weatherDesc { get; set; }
public List<WeatherIconUrl> weatherIconUrl { get; set; }
public float precipMM { get; set; }
}
public class WeatherDesc
{
public string value { get; set; }
}
public class WeatherIconUrl
{
public string value { get; set; }
}
}

You need to update the class to match the schema of the XML structure (these are case sensitive).
You can start with your existing file using the attributes found in System.Xml.Serialization.
[XmlRoot("data")]
public class Data {
// and so on..
}
Or you could use the XSD tool to generate the class for you following these steps.
Create schema for the XML returns from the service (Xml -> Create Schema)
In VS Studio tools run this command: XSD XmlSchema.xsd /c (where XmlSchema.xsd is the schema produced in step 1).

The way that your model is set up right now, you have LocalWeather as the root, whereas in the actual XML the root is Data. That's why you're getting the "Invalid root node" error. So, instead of
XmlSerializer des = new XmlSerializer(typeof(LocalWeather));
StreamReader tr = new StreamReader(result);
Object obj = des.Deserialize(tr);
LocalWeather data = (LocalWeather)obj;
try
XmlSerializer des = new XmlSerializer(typeof(Data));
StreamReader tr = new StreamReader(result);
Object obj = des.Deserialize(tr);
Data data = (Data)obj;

Related

Retrieve XML column from DataBase with lines C#

I run query against DB which returns me 1 row 2 columns. Each column has XML(script) inside which I need to retrieve into (ideally string) and then execute against DB.
I need the retrieved string to have lines and formatting as if i would copy if from SQL management studio.
Part of XMLresult from SQL management studio I need this format. replacement: XXXXXX
<message>
<header>
<meta version="02" type="OrMessageUdalost_Int" />
<sender name="XXXXXX" appid="XXXXXX" netid="XXXXXX" />
<receiver name="XXXXXX" appid="XXXXXX" netid="XXXXXX" />
<timestamp date="XXXXXX" time="10:11:00" gmt="+XXXXXX" />
<options priority="4" props="XXXXXX" limit="100" />
</header>
<content>
<q1:orMessageUdalost_Int xmlns:q1="XXXXXX" verze="v_2.11">
<hlavicka>
<idDatovaVeta>XXXXXX</idDatovaVeta>
<datumVytvoreni>XXXXXX</datumVytvoreni>
<ciselnikAktualizace>false</ciselnikAktualizace>
<ostrovniRezim>false</ostrovniRezim>
<puvodceDV>
<id>XXXXXX</id>
<kod>XXXXXX</kod>
</puvodceDV>
<idPuvodniDV>XXXXXX</idPuvodniDV>
<puvodniDatumVytvoreni>XXXXXX</puvodniDatumVytvoreni>
<stavUdalosti>XXXXXX</stavUdalosti>
<stavSlozky>
<slozka>
<id>XXXXXX</id>
<kod>XXXXXX</kod>
</slozka>
<isStav>XXXXXX</isStav>
</stavSlozky>
</hlavicka>
<teloFull>
Thanks for any advice.
So the key is to get the proper indentation?
In that case, I would recommend taking a look at the following SO thread:
Format XML string to print friendly XML string
The key is that you need indentation, which can be achieved through the XmlTextWrite.Formatting = Formatting.Indented option.
Use XML serializer. See code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication193
{
class Program
{
const string INPUT_FILENAME = #"c:\temp\test.xml";
const string OUTPUT_FILENAME = #"c:\temp\test1.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(INPUT_FILENAME);
StringReader sReader = new StringReader(xml);
XmlReader reader = XmlReader.Create(sReader);
XmlSerializer serializer = new XmlSerializer(typeof(Message));
Message message = (Message)serializer.Deserialize(reader);
//write
XmlSerializerNamespaces names = new XmlSerializerNamespaces();
names.Add("q1", "XXXXXX");
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
MemoryStream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream);
serializer.Serialize(writer,message,names);
byte[] buffer = new byte[stream.Length];
stream.Position = 0;
stream.Read(buffer, 0, (int)stream.Length);
string output = Encoding.UTF8.GetString(buffer);
}
}
[XmlRoot("message")]
public class Message
{
public Header header { get; set; }
public Content content { get; set; }
}
public class Header
{
public Meta meta { get; set; }
public Sender sender { get; set; }
public Receiver receiver { get; set; }
public Timestamp timestamp { get; set; }
public Options options { get; set; }
}
public class Meta
{
[XmlAttribute("version")]
public string version { get; set; }
[XmlAttribute("type")]
public string type { get; set; }
}
public class Sender
{
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public string appid { get; set; }
[XmlAttribute()]
public string netid { get; set; }
}
public class Receiver
{
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public string appid { get; set; }
[XmlAttribute()]
public string netid { get; set; }
}
public class Timestamp
{
[XmlAttribute()]
public string date { get; set; }
[XmlAttribute()]
public DateTime timespan { get; set; }
[XmlAttribute()]
public string gmt { get; set; }
}
public class Options
{
[XmlAttribute()]
public int priority { get; set; }
[XmlAttribute()]
public string props { get; set; }
[XmlAttribute()]
public int limit { get; set; }
}
public class Content
{
[XmlElement(Namespace = "XXXXXX")]
public OrMessageUdalost_Int orMessageUdalost_Int { get; set; }
}
public class OrMessageUdalost_Int
{
[XmlAttribute()]
public string verze { get; set; }
[XmlElement(Namespace = "")]
public Hlavicka hlavicka { get; set; }
}
public class Hlavicka
{
public string idDatovaVeta { get; set; }
public string datumVytvoreni { get; set; }
public string ciselnikAktualizace { get; set; }
public Boolean ostrovniRezim { get; set; }
public PuvodceDV puvodceDV { get; set; }
public string idPuvodniDV { get; set; }
public string puvodniDatumVytvoreni { get; set; }
public string stavUdalosti { get; set; }
[XmlArray("stavSlozky")]
[XmlArrayItem("slozka")]
public List<Slozka> slozka { get; set; }
public TeloFull teloFull { get; set; }
}
public class PuvodceDV
{
public string id { get; set; }
public string kod { get; set; }
}
public class Slozka
{
public string id { get; set; }
public string kod { get; set; }
}
public class TeloFull
{
}
}

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; }
}
}

Deserializing JSON objects, keep getting errors (C#)

I am trying to deserialize my json code. The json code is in a string, and the json code looks like this (so I'm assuming it's json objects)
{
"post_id":13,
"thread_id":9,
"user_id":1,
"username":"Username",
"post_date":1496439611,
"message":"testzilla - 2133746943A9",
"ip_id":698,
"message_state":"visible",
"attach_count":0,
"position":0,
"likes":0,
"like_users":"a:0:{}",
"warning_id":0,
"warning_message":"",
"last_edit_date":1496476199,
"last_edit_user_id":0,
"edit_count":9,
"node_id":34,
"title":"Test",
"tags":"a:0:{}",
"node_title":"test node",
"node_name":null,
"message_html":"testzilla - 2133746943A9",
"absolute_url":"url"
}
How would I put the "message" container inside a string? So that the string would contain "testzilla - 2133746943A9" without the quotation marks. I am using JSON.Net
The name of the string that contains this json code is "MACs". Thanks in advance. PS: I am a new coder.
there is a missing "{" at the beginning of your json file, try adding it
You need to create your c# class to deserialize your json string. As per your json structure i have created your class given below
public class MyClass
{
public int post_id { get; set; }
public int thread_id { get; set; }
public int user_id { get; set; }
public string username { get; set; }
public int post_date { get; set; }
public string message { get; set; }
public int ip_id { get; set; }
public string message_state { get; set; }
public int attach_count { get; set; }
public int position { get; set; }
public int likes { get; set; }
public string like_users { get; set; }
public int warning_id { get; set; }
public string warning_message { get; set; }
public int last_edit_date { get; set; }
public int last_edit_user_id { get; set; }
public int edit_count { get; set; }
public int node_id { get; set; }
public string title { get; set; }
public string tags { get; set; }
public string node_title { get; set; }
public object node_name { get; set; }
public string message_html { get; set; }
public string absolute_url { get; set; }
}
No need to use library JSON.Net. You can do this by simply using System.Web.Script.Serialization to deserialize the json string.
Note : System.Web.Script.Serialization is available inside System.Web.Extensions namespace.
Below is the complete code. I kept your json data inside a file named as "test2.json" and consuming it from that file.
using System;
using System.Web.Script.Serialization;
using System.IO;
namespace DesrializeJson1ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var jsonFile = "test2.json";
string jsonstring = File.ReadAllText(jsonFile);
var serializer = new JavaScriptSerializer();
MyClass aClass = serializer.Deserialize<MyClass>(jsonstring);
Console.WriteLine("--------------------------");
Console.WriteLine("message :" + aClass.message);
Console.WriteLine("message_state :" + aClass.message_state);
Console.WriteLine("warning_message :" + aClass.warning_message);
Console.WriteLine("message_html :" + aClass.message_html);
Console.WriteLine("--------------------------");
Console.Read();
}
}
public class MyClass
{
public int post_id { get; set; }
public int thread_id { get; set; }
public int user_id { get; set; }
public string username { get; set; }
public int post_date { get; set; }
public string message { get; set; }
public int ip_id { get; set; }
public string message_state { get; set; }
public int attach_count { get; set; }
public int position { get; set; }
public int likes { get; set; }
public string like_users { get; set; }
public int warning_id { get; set; }
public string warning_message { get; set; }
public int last_edit_date { get; set; }
public int last_edit_user_id { get; set; }
public int edit_count { get; set; }
public int node_id { get; set; }
public string title { get; set; }
public string tags { get; set; }
public string node_title { get; set; }
public object node_name { get; set; }
public string message_html { get; set; }
public string absolute_url { get; set; }
}
}
OUTPUT
You can use regex to get the value you want.
string yourJsonString = #"{ ""post_id"":13, ""thread_id"":9, ""user_id"":1, ""username"":""Username"", ""post_date"":1496439611, ""message"":""testzilla - 2133746943A9"", ""ip_id"":698, ""message_state"":""visible"", ""attach_count"":0, ""position"":0, ""likes"":0, ""like_users"":""a:0:{}"", ""warning_id"":0, ""warning_message"":"""", ""last_edit_date"":1496476199, ""last_edit_user_id"":0, ""edit_count"":9, ""node_id"":34, ""title"":""Test"", ""tags"":""a:0:{}"", ""node_title"":""test node"", ""node_name"":null, ""message_html"":""testzilla - 2133746943A9"", ""absolute_url"":""url""}";
string value = System.Text.RegularExpressions.Regex.Match(yourJsonString,#"""message"":(.+?),").Groups[1].Value.Replace(#"""","");
MessageBox.Show(value);
You can also use dynamic type for deserialization. You will no need to write object for deserialization:
var str = "{\r\n \"post_id\":13,\r\n \"thread_id\":9,\r\n \"user_id\":1,\r\n \"username\":\"Username\",\r\n \"post_date\":1496439611,\r\n \"message\":\"testzilla - 2133746943A9\",\r\n \"ip_id\":698,\r\n \"message_state\":\"visible\",\r\n \"attach_count\":0,\r\n \"position\":0,\r\n \"likes\":0,\r\n \"like_users\":\"a:0:{}\",\r\n \"warning_id\":0,\r\n \"warning_message\":\"\",\r\n \"last_edit_date\":1496476199,\r\n \"last_edit_user_id\":0,\r\n \"edit_count\":9,\r\n \"node_id\":34,\r\n \"title\":\"Test\",\r\n \"tags\":\"a:0:{}\",\r\n \"node_title\":\"test node\",\r\n \"node_name\":null,\r\n \"message_html\":\"testzilla - 2133746943A9\",\r\n \"absolute_url\":\"url\"\r\n}";
dynamic obj = JsonConvert.DeserializeObject(str);
var postId = obj.post_id;
Console.WriteLine("postId:" + postId);
output:
postId:13

Deserialization not filling data - C#

I am trying to deserialize an XML .
Sample XML is given below
<?xml version="1.0" ?>
<TRANSACTION_RESPONSE>
<TRANSACTION>
<TRANSACTION_ID>25429</TRANSACTION_ID>
<MERCHANT_ACC_NO>02700701354375000964</MERCHANT_ACC_NO>
<TXN_STATUS>F</TXN_STATUS>
<TXN_SIGNATURE>a16af68d4c3e2280e44bd7c2c23f2af6cb1f0e5a28c266ea741608e72b1a5e4224da5b975909cc43c53b6c0f7f1bbf0820269caa3e350dd1812484edc499b279</TXN_SIGNATURE>
<TXN_SIGNATURE2>B1684258EA112C8B5BA51F73CDA9864D1BB98E04F5A78B67A3E539BEF96CCF4D16CFF6B9E04818B50E855E0783BB075309D112CA596BDC49F9738C4BF3AA1FB4</TXN_SIGNATURE2>
<TRAN_DATE>29-09-2015 07:36:59</TRAN_DATE>
<MERCHANT_TRANID>150929093703RUDZMX4</MERCHANT_TRANID>
<RESPONSE_CODE>9967</RESPONSE_CODE>
<RESPONSE_DESC>Bank rejected transaction!</RESPONSE_DESC>
<CUSTOMER_ID>RUDZMX</CUSTOMER_ID>
<AUTH_ID />
<AUTH_DATE />
<CAPTURE_DATE />
<SALES_DATE />
<VOID_REV_DATE />
<REFUND_DATE />
<REFUND_AMOUNT>0.00</REFUND_AMOUNT>
</TRANSACTION>
</TRANSACTION_RESPONSE>
Following is the Class
[XmlType("TRANSACTION_RESPONSE")]
public class BankQueryResponse
{
[XmlElement("TRANSACTION_ID")]
public string TransactionId { get; set; }
[XmlElement("MERCHANT_ACC_NO")]
public string MerchantAccNo { get; set; }
[XmlElement("TXN_SIGNATURE")]
public string TxnSignature { get; set; }
[XmlElement("TRAN_DATE")]
public DateTime TranDate { get; set; }
[XmlElement("TXN_STATUS")]
public string TxnStatus { get; set; }
[XmlElement("REFUND_DATE")]
public DateTime RefundDate { get; set; }
[XmlElement("RESPONSE_CODE")]
public string ResponseCode { get; set; }
[XmlElement("RESPONSE_DESC")]
public string ResponseDesc { get; set; }
[XmlAttribute("MERCHANT_TRANID")]
public string MerchantTranId { get; set; }
}
The deserialization code is
BankQueryResponse result = new BankQueryResponse();
if(!string.IsNullOrEmpty(responseData))
{
XmlSerializer serializer = new XmlSerializer(typeof(BankQueryResponse));
using(TextReader xmlreader = new StringReader(responseData))
{
result = (BankQueryResponse) serializer.Deserialize(xmlreader);
}
}
I am getting all value in result as null . I am not sure whats the reason . Can some one throws a light into the issue. Am i missing something while deserialising
You should modify the code something like this
[XmlType("TRANSACTION_RESPONSE")]
public class TransactionResponse
{
[XmlElement("TRANSACTION")]
public BankQueryResponse Response { get; set; }
}
This will change like this
public class BankQueryResponse
{
[XmlElement("TRANSACTION_ID")]
public string TransactionId { get; set; }
[XmlElement("MERCHANT_ACC_NO")]
public string MerchantAccNo { get; set; }
[XmlElement("TXN_SIGNATURE")]
public string TxnSignature { get; set; }
[XmlElement("TRAN_DATE")]
public DateTime TranDate { get; set; }
[XmlElement("TXN_STATUS")]
public string TxnStatus { get; set; }
[XmlElement("REFUND_DATE")]
public DateTime RefundDate { get; set; }
[XmlElement("RESPONSE_CODE")]
public string ResponseCode { get; set; }
[XmlElement("RESPONSE_DESC")]
public string ResponseDesc { get; set; }
[XmlAttribute("MERCHANT_TRANID")]
public string MerchantTranId { get; set; }
}
Deseralization Code would be something like this
TransactionResponse result = new TransactionResponse();
if(!string.IsNullOrEmpty(responseData))
{
XmlSerializer serializer = new XmlSerializer(typeof(TransactionResponse));
using(TextReader xmlreader = new StringReader(responseData))
{
result = (TransactionResponse) serializer.Deserialize(xmlreader);
}
}

How do I deserialise this JSON?

I haven't done anything with JSON before... so I am probably just missing a step.
Here is an example of the JSON I want to deserialise:
{"item":{"icon":"http://services.runescape.com/m=itemdb_rs/4765_obj_sprite.gif?id=4798","icon_large":"http://services.runescape.com/m=itemdb_rs/4765_obj_big.gif?id=4798","id":4798,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant brutal","description":"Blunt adamantite arrow...ouch","current":{"trend":"neutral","price":237},"today":{"trend":"neutral","price":0},"members":"true","day30":{"trend":"positive","change":"+1.0%"},"day90":{"trend":"negative","change":"-0.0%"},"day180":{"trend":"positive","change":"+0.0%"}}}
I put this into "Json 2 C#" and ended up creating this new .cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RSTool.Models
{
public class Current
{
public string trend { get; set; }
public int price { get; set; }
}
public class Today
{
public string trend { get; set; }
public int price { get; set; }
}
public class Day30
{
public string trend { get; set; }
public string change { get; set; }
}
public class Day90
{
public string trend { get; set; }
public string change { get; set; }
}
public class Day180
{
public string trend { get; set; }
public string change { get; set; }
}
public class Item
{
public string icon { get; set; }
public string icon_large { get; set; }
public int id { get; set; }
public string type { get; set; }
public string typeIcon { get; set; }
public string name { get; set; }
public string description { get; set; }
public Current current { get; set; }
public Today today { get; set; }
public string members { get; set; }
public Day30 day30 { get; set; }
public Day90 day90 { get; set; }
public Day180 day180 { get; set; }
}
public class RootObject
{
public Item item { get; set; }
}
}
So, I have the class. I can retrieve the JSON from its location as a string, but I really have no idea how to deserialise it... I have installed Newtonsoft.Json and have tried using PopulateObject and also Deserializer but not with any luck...
Assuming that my JSON is stored as a string called "json", how would I go about storing that query and then retrieving the item name, for example?
Use:
var deserialized = JsonConvert.DeserializeObject<RootObject>(json);
I just tested this successfully given the code you supplied.
You can then access properties of object as normal:
MessageBox.Show(deserialized.item.name);

Categories