How can I convert this Class into XML ? Or is there any possible way I can convert a JSON String for the same class directly into XML ? I am not getting an idea or a sample code to start with the conversion.
public class Contacts
{
public Datum[] data { get; set; }
public Info info { get; set; }
}
public class Datum
{
public Owner Owner { get; set; }
public object Email { get; set; }
public string Description { get; set; }
public string currency_symbol { get; set; }
public string Mailing_Zip { get; set; }
}
public class Owner
{
public string name { get; set; }
public string id { get; set; }
}
public class Info
{
public int per_page { get; set; }
public int count { get; set; }
public int page { get; set; }
public bool more_records { get; set; }
}
Please help in converting the Class to XML or the JSON String based on the above class into an XML directly.
The scenario is that, I am receiving a JSON result from the API and this result needs to be processed in the SQL Server where the datatype has been kept as XML. I am hoping that this can be achieved successfully.
There are plenty of online resources to convert c# properties in to JSON or XML without any effort , try this and this and JSON to XML converter this too
Update
If you wish to convert inside the code try below. p.s (use Json.NET)
string json = //set your result JSON from the web API call;
XNode node = JsonConvert.DeserializeXNode(json, "Root");
Console.WriteLine(node.ToString());
this will convert your Json to XML
I solved the same converting the JSON to Class object and serializing the XML from the Class object.
public static string GetXMLFromObject(object o)
{
StringWriter sw = new StringWriter();
XmlTextWriter tw = null;
try
{
XmlSerializer serializer = new XmlSerializer(o.GetType());
tw = new XmlTextWriter(sw);
serializer.Serialize(tw, o);
}
catch (Exception ex)
{
//Handle Exception Code
}
finally
{
sw.Close();
if (tw != null)
{
tw.Close();
}
}
return sw.ToString();
}
Related
In web service i am try to convert a jzonString to a list.
{
"name": "Test",
"Fname": "Testing",
"S1": "Content1",
"S2": "Content2",
"S3": "Content3"
}
[WebMethod]
public int Create(string Detils, string Companyid)
{
try
{
dynamic ScheduleShift = new JavaScriptSerializer().DeserializeObject(Detils);
\\ i need to set data to list or to an object
InvDetails objDetails = new InvDetails();
List<InvDetails> lstDetails = new List<InvDetails>();
return objDetails.CreateInvDetails(objDetils);
}
catch (Exception ex)
{
// Abort Transaction
throw ex;
}
}
Created another library file to declare the object and to insert into db
public class Inventory
{
CommonExecDAL CommonExecDAL = new CommonExecDAL();
public string name { get; set; }
public string Fname { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public int intCompanyId { get; set; }
public int CreateInvComputer(InvDetails objInvDetails)
{
SqlParameter[] arParms = new SqlParameter[6];
.........
}
}
If you don't want to create a class :
You can use JObject.Parse() method for deserializing dynamically.
As #SirRufo said, you can deserialize a JSON array into a list. but your JSON string in the sample is a single object!
Anyway, you deserialize JSON string to object with the use JSON.Net.
First, you have a class for Deserialize :
public class Data
{
public string name { get; set; }
public string Fname { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
}
Then you can deserialize JSON string to C# class :
var obj = JsonConvert.DeserializeObject<Data>(jsonString);
Just add reference to System.Web.Extensions ,(built in dll on .NET 4+) :
JavaScriptSerializer jss = new JavaScriptSerializer();
var jsonObj =jss.Deserialize<dynamic>(jsonString);
I want to use the json values in my c# code. So I have written the code like below
public static void WriteToIEMService(string jsonValue)
{
string TimeFormatText = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");
string strFileCreationDate = DateTime.Now.ToString("dd/MM/yyyy");
string strFileName = ConfigurationManager.AppSettings["IEM_SERVICEFILE"].ToString();
try
{
using (StreamWriter sw = File.CreateText(ConfigurationManager.AppSettings["LogFileDirectory"].ToString() + strFileName + "_" + strFileCreationDate + ".txt"))
{
List<MasterServiceResponse> records = JsonConvert.DeserializeObject<List<MasterServiceResponse>>(jsonValue);
sw.WriteLine("IEM Service started and send data to IEM below");
foreach (MasterServiceResponse record in records)
{
sw.WriteLine(record.SapId);
}
}
}
catch (Exception)
{
throw;
}
}
But I am getting error as
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[IPColoBilling_BKP.App_Code.MasterServiceResponse]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Please help
EDIT
My json values is as below
{"SiteData":[{"SAPId":"I-UW-SRPR-ENB-I001","SiteRFEIDate":"03-11-2014","SiteRFSDate":"03-11-2014","ID_OD":"ID","ID_ODchangeDate":"04-11-2018","NoofRRHBase":"0","RRHBaseChangeEffectiveDate":"","No_Of_Tenancy":"3","TenancyChangeEffectiveDate":"03-11-2014","SiteStatus":"Active","SiteDropDate":""}]}
UPDATE
public class MasterServiceResponse
{
public string SapId { get; set; }
public string AcknowledgementID { get; set; }
public string FlagResponse { get; set; }
public string ResponseMessage { get; set; }
public string GisStatus { get; set; }
public string GisSendDate { get; set; }
public string SiteRFEIDate { get; set; }
public string SiteRFSDate { get; set; }
public string SiteRRHDate { get; set; }
public string NoofRRHBase { get; set; }
}
Update: A stated by Panagiotis Kanavos, You are not creating Root object, so you have to restructure your models.
Don't know what your Model looks like, But this error message says your giving json object where it is expecting JSON array,
Below is the model you should be using
public class SiteData
{
public string SAPId { get; set; }
public string SiteRFEIDate { get; set; }
public string SiteRFSDate { get; set; }
public string ID_OD { get; set; }
public string ID_ODchangeDate { get; set; }
public string NoofRRHBase { get; set; }
public string RRHBaseChangeEffectiveDate { get; set; }
public string No_Of_Tenancy { get; set; }
public string TenancyChangeEffectiveDate { get; set; }
public string SiteStatus { get; set; }
public string SiteDropDate { get; set; }
}
public class RootObject
{
public List<SiteData> SiteData { get; set; }
}
You also have to change the deserializing code
E.g.
RootObject records = JsonConvert.DeserializeObject<RootObject>(jsonValue);
foreach (SiteData record in records.SiteData)
{
sw.WriteLine(record.SapId);
}
As the error mentions, you cannot deserialize JSON object to list. So instead of:
List<MasterServiceResponse> records = JsonConvert.DeserializeObject<List<MasterServiceResponse>>(jsonValue);
You should update have something like:
MyObject obj = JsonConvert.DeserializeObject<MyObject>(jsonValue);
The exception message tells you that the JSON string contains single object, but you're tried to deserialize it into List<MasterServiceResponse> collection.
You should create a class to hold List<MasterServiceResponse>:
public class SiteData
{
public List<MasterServiceResponse> MasterServiceResponse { get; set; }
}
Then you should replace this line:
List<MasterServiceResponse> records = JsonConvert.DeserializeObject<List<MasterServiceResponse>>(jsonValue);
to return single object like this:
SiteData records = JsonConvert.DeserializeObject<SiteData>(jsonValue);
Reference:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1
Because your JSON start with a key "SiteData" which has an array value, you need to create a helper class to match that structure (e.g. class SiteResponse) with a property named SiteData of type List<MasterServiceResponse>.
Code:
public class SiteResponse
{
public List<MasterServiceResponse> SiteData { get; set; }
}
private static void TestJson()
{
var jsonValue = "{\"SiteData\":[{\"SAPId\":\"I-UW-SRPR-ENB-I001\",\"SiteRFEIDate\":\"03-11-2014\",\"SiteRFSDate\":\"03-11-2014\",\"ID_OD\":\"ID\",\"ID_ODchangeDate\":\"04-11-2018\",\"NoofRRHBase\":\"0\",\"RRHBaseChangeEffectiveDate\":\"\",\"No_Of_Tenancy\":\"3\",\"TenancyChangeEffectiveDate\":\"03-11-2014\",\"SiteStatus\":\"Active\",\"SiteDropDate\":\"\"}]}";
var siteResponse = JsonConvert.DeserializeObject<SiteResponse>(jsonValue);
List<MasterServiceResponse> records = siteResponse.SiteData;
}
Working demo here:
https://dotnetfiddle.net/wzg8AK
I have class structure as follows
public class Common
{
public int price { get; set; }
public string color { get; set; }
}
public class SampleProduct:Common
{
public string sample1 { get; set; }
public string sample2 { get; set; }
public string sample3 { get; set; }
}
I have XML file as follows
<ConfigData>
<Common>
<price>1234</price>
<color>pink</color>
</Common>
<SampleProduct>
<sample1>new</sample1>
<sample2>new</sample2>
<sample3>new123</sample3>
</SampleProduct>
</ConfigData>
Now I wanted to deserialize full XML data to SampleProduct object (single object).I can deserialize XML data to different object but not in a single object. Please help.
If you create the XML yourself Just do it like this:
<ConfigData>
<SampleProduct>
<price>1234</price>
<color>pink</color>
<sample1>new</sample1>
<sample2>new</sample2>
<sample3>new123</sample3>
</SampleProduct>
</ConfigData>
Otherwise, if you get the XML from other sources, do what Kayani suggested in his comment:
public class ConfigData
{
public Common { get; set; }
public SampleProduct { get; set; }
}
But don't forget that the SampleProduct created in this manner don't have "price" and "color" properties and these should be set using created Common instance
Here is the complete solution using the provided XML from you.
public static void Main(string[] args)
{
DeserializeXml(#"C:\sample.xml");
}
public static void DeserializeXml(string xmlPath)
{
try
{
var xmlSerializer = new XmlSerializer(typeof(ConfigData));
using (var xmlFile = new FileStream(xmlPath, FileMode.Open))
{
var configDataOSinglebject = (ConfigData)xmlSerializer.Deserialize(xmlFile);
xmlFile.Close();
}
}
catch (Exception e)
{
throw new ArgumentException("Something went wrong while interpreting the xml file: " + e.Message);
}
}
[XmlRoot("ConfigData")]
public class ConfigData
{
[XmlElement("Common")]
public Common Common { get; set; }
[XmlElement("SampleProduct")]
public SampleProduct XSampleProduct { get; set; }
}
public class Common
{
[XmlElement("price")]
public string Price { get; set; }
[XmlElement("color")]
public string Color { get; set; }
}
public class SampleProduct
{
[XmlElement("sample1")]
public string Sample1 { get; set; }
[XmlElement("sample2")]
public string Sample2 { get; set; }
[XmlElement("sample3")]
public string Sample3 { get; set; }
}
This will give you a single Object with all the elements you need.
I have some json data stored in a text file (the data is at https://github.com/VinceG/Auto-Cars-Makes-And-Models). I've run the json file through json2csharp which has generated the following classes for storage
public class Model
{
public string value { get; set; }
public string title { get; set; }
}
public class VehicleMake
{
public string value { get; set; }
public string title { get; set; }
public List<Model> models { get; set; }
}
I am trying to deserialise the data into the VehicleMake class using the following code
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Let's deserialise!");
var sb = new StringBuilder();
using (var sr = new StreamReader("models.json"))
{
string line;
while ((line = sr.ReadLine()) != null)
sb.AppendLine(line);
}
var vehicleList = Deserialize<VehicleMake>(sb.ToString());
Console.WriteLine("Done");
}
private static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
try
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception throw in Deserialize - {0}-{1}", ex.Message, ex.StackTrace);
return obj;
}
}
}
I've used this deserialize method in a number of different project and it has never caused an issue. Here though it is returning null into the vehicleList object.
The string builder.ToString() looks to contain all of the data (it is showing Other Yugo Models for the the final title which is correct)
I'm deliberately not using json.net as it's the only deserialisation of json I'm doing within this application and so it's somewhat overkill.
I should say that this isn't a homework project or anything like that
The json string represents an array, so you need to deserialize it to a List<VehicleMake>. Just change the following line:
var vehicleList = Deserialize<VehicleMake>(sb.ToString());
with:
var vehicleList = Deserialize<List<VehicleMake>>(sb.ToString());
You'll get a list of vehicles with properly initialized value, title and models properties.
You need to add [DataContract] and [DataMember] attributes to your class and members. Possibly also [Serializable]
using System;
using System.Runtime.Serialization;
[Serializable]
[DataContract]
public class Model
{
[DataMember(Name = "value")]
public string value { get; set; }
[DataMember(Name = "title")]
public string title { get; set; }
}
[Serializable]
[DataContract]
public class VehicleMake
{
[DataMember(Name = "value")]
public string value { get; set; }
[DataMember(Name = "title")]
public string title { get; set; }
[DataMember(Name = "models")]
public List<Model> models { get; set; }
}
I made a call to a web server called Sample ApI. I want to be able to parse that data that's in json or xml, either would be nice and display it in a table format. This is what I have so far.
All I want is to be able to parse the data that's in this string _responseAsString and display a table. I don't know how to start it, I just know JavaScriptSerialzer parseXXX = new Java...lizer(). Please help me or assist in the right direction.
public class Event
{
public string event_key { get; set; }
public string user_token { get; set; }
public string event_set_key { get; set; }
public string event_type { get; set; }
public string event_date { get; set; }
public string event_amount { get; set; }
public string event_location_key { get; set; }
public string event_location_name { get; set; }
public string event_location_city { get; set; }
public string event_location_state { get; set; }
public string event_location_country { get; set; }
public string event_acknowledged { get; set; }
}
public ActionResult GetEvent()
{
try
{
string at = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
string et = "KI2XfwQNByLPFdK4i3a74slLT7sjjzYRi9RR7zEtCoQ%3D";
string t = "20111128183020";
string _checkingUrl = String.Format("http://172.22.22.10/SampleAPI/Event/GetEvents?at={0}&et={1}&t={2}&responseFormat=json", at, et, t);
System.Net.HttpWebRequest request=System.Net.WebRequest.Create(_checkingUrl) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response=request.GetResponse() as System.Net.HttpWebResponse;
System.IO.StreamReader _readResponse=new System.IO.StreamReader(response.GetResponseStream());
//The encrypted dynamics response in either xml or json
string _responseAsString=_readResponse.ReadToEnd();
JavaScriptSerializer parseResponse = new JavaScriptSerializer();
List<Event> events = parseResponse.Deserialize<List<Event>>(_responseAsString);
// this below is to make sure i was receiving my json data.
return Content(_responseAsString);
_readResponse.Close();
}
catch (Exception e)
{
//log error
}
return View();
}
This is the json data I receive when I make the http request:
"[{\"event_key\":\"cc2a1802-2b04-4530-ad50-0d4f0ed19dd3\",\"user_token\":\"40e62a11-40c4-408d-8cdd-1293cbaf9a41\",\"event_set_key\":\"615017f2-ae28-4b8d-9def-cf043642b928\",\"event_type\":\"Arrival\",\"event_date\":\"6/20/2011
4:15:28
PM\",\"event_amount\":\"100\",\"event_location_key\":\"50fc1c22-d77b-4a91-b31d-da036827060b\",\"event_location_name\":\"Store2\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"True\"},{\"event_key\":\"2ac9e25e-137c-4a72-8cc5-157d67ea66c1\",\"user_token\":\"58cb4fcd-e140-4232-88c9-06eecb95b63d\",\"event_set_key\":\"00710ca7-f5d7-4c7a-bbfb-95491ae278ef\",\"event_type\":\"Arrival\",\"event_date\":\"9/23/2011
4:15:28
PM\",\"event_amount\":\"45\",\"event_location_key\":\"5a732dd5-9459-4cdd-a980-f3daf1a07343\",\"event_location_name\":\"Store4\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"False\"},{\"event_key\":\"386b1fa1-11b2-48d9-b7f1-4bbe21ced487\",\"user_token\":\"c3d8b7ff-d85f-42a8-98f6-e091b48c2280\",\"event_set_key\":\"dc55843b-f8cf-4e8a-9091-188ce0609fe1\",\"event_type\":\"Arrival\",\"event_date\":\"9/18/2011
4:15:28
PM\",\"event_amount\":\"100\",\"event_location_key\":\"be6d4fb4-c0e3-4303-b70d-7a22b721aa56\",\"event_location_name\":\"Store1\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"False\"}]"
The JSON website has some good information on this.
For older browsers, you would eval the string (with some brackets to make it work):
var myObject = eval('(' + myJsonText + ')');
And these days, we tend to use
JSON.parse(myJsonText);
And server side, in C#
var serializer = new JavaScriptSerializer();
T obj = serializer.Deserialize<T>(myJsonText);
First of all...
If you're just passing through the JSON message returned from some other API, why not just return their response string verbatim (in other words, why deserialize it at all)?
public ActionResult GetEvent()
{
string at = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
string et = "KI2XfwQNByLPFdK4i3a74slLT7sjjzYRi9RR7zEtCoQ%3D";
string t = "20111128183020";
string _checkingUrl = String.Format("http://172.22.22.10/SampleAPI/Event/GetEvents?at={0}&et={1}&t={2}&responseFormat=json", at, et, t);
System.Net.HttpWebRequest request=System.Net.WebRequest.Create(_checkingUrl) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response=request.GetResponse() as System.Net.HttpWebResponse;
using (var readResponse= new StreamReader(response.GetResponseStream()))
{
return Content(readResponse.ReadToEnd(), "application/json");
}
}
Then read on
It's possible to use a JSON text reader to break apart the JSON message into a table of name/value pairs, but I think that's missing the point in your case. If the message is constant, just create a class that represents each element in the JSON message and parse it. I used json2csharp to stub such a class:
public class Event
{
public string event_key { get; set; }
public string user_token { get; set; }
public string event_set_key { get; set; }
public string event_type { get; set; }
public string event_date { get; set; }
public string event_amount { get; set; }
public string event_location_key { get; set; }
public string event_location_name { get; set; }
public string event_location_city { get; set; }
public string event_location_state { get; set; }
public string event_location_country { get; set; }
public string event_location_lat { get; set; }
public string event_location_long { get; set; }
public string event_description { get; set; }
public string event_acknowledged { get; set; }
}
Then use your favorite JSON serializer to deserialize into a list of these objects:
var serializer = new JavaScriptSerializer();
var events = serializer.Deserialize<List<Event>>(responseAsString);
(I prefer JSON.NET, here's the equivalent to the block above)
var events = JsonConvert.DeserializeObject<List<Event>>(responseAsString);
If you actually do need to be able to read a stream of text and generically create a table of name/value pairs, I'd use JSON.NET's LINQ-to-JSON or the JsonTextReader.