Deserializing multiple XML documents into objects with same class names - c#

I have a API that I am sending requests to and receiving responses from, to start with I de-serialize a XML request template into a class object, which was just generated by using the paste XML as class option in Visual Studio, then amend the data in a few elements as needed, before serializing back into XML string and sending the request.
When I receive the response, I would also like to de-serialize this as there are a lot of repeated tags, so would be easier to get exact values out by doing:
var myvar = Root.Widgets.Widget1.WidgetPrices.PriceInPounds.value
The issue is if I get the XML response and paste it as a class object, I then have two classes with the same name because both the Request and Response share some but not all of the same structure, i.e both will contain Root.Widgets. And if I change any of the class object names, then the XML won't de-serialize properly into it. I'm not sure how to get around this so any suggestions appreciated.

Related

How to dynamically validate a JSON with a JSchema

I receive flattened json properties in the following format:
jsonName.propertyPath1.propertyPath2..., value
Example:
UniversityCollection.Persons.Person1.Name, Dave
I need to validate these kind of properties with a JSchema, that a receive from a file before generating a JObject with all the properties. I just have the program that collect them and generate the JObject.
It is important to note that i do not have knowledge about neither the structure of the Json nor the Json schema. I want to make a general program that validates any Json received through its associated Json schema.

Returning JSON string from 3rd party API in ASP.Net MVC controller

I'm wrapping a third-party API in a controller (due to security hoops we have to jump through) and the API returns a JSON string.
I do some minor changes to the JSON string and want to return that string.
I don't see a way to do that with a JSONResult, as it requires an object, and returning JSON string is sent back as a string.
Am I stuck with using something like a ContentResult?
JSONLint.com says the modified JSON is valid. It starts with...
[{"Acknowledgment Start Date":null,"Additional Location Details":null,"Area Code":null,"Assign To Vendor":"No",...
If I use the Newtonsoft.Json.JsonConvert(), it does this to my JSON string...
[[[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],...
If I use JavaScriptSerializer, I get this again...
[[[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],...
I suspect part of the problem is the null values in the JSON string.
Is there another solution? Are there issues with using a ContentResult that I'm not aware of?
Newtonsoft.Json.JsonConvert() serializes an object, it doesn't parse (AKA deserialize) it. What you're doing when you call Newtonsoft.Json.JsonConvert(jsonString) is you're saying "serialize this JSON string to JSON". So, you get a funky result.
You could instead parse the JSON, then make your modifications, then serialize it again. For example:
var myObject = Newtonsoft.Json.DeserializeObject<POCOClass>(jsonString);
myObject.Whatever = "123";
//... etc.
This of course after defining your POCO class like such:
public class POCOClass {
[JsonProperty(PropertyName = "Acknowledgment Start Date")]
public string AcknowledgmentStartDate { get; set; }
// etc.
}
Then when you're done, serialize it back:
jsonString = Newtonsoft.Json.JsonConvert(myObject) // or Newtonsoft.Json.SerializeObject(myObject)
Upon closer inspection, I had a couple of realizations.
The first being that the outputted JSON isn't valid because the quoted identifiers include spaces and colons. For example, this one from above.
... ,"Additional Location Details":null, ...
While I suspect this is the root of problems, I don't have the time to write a parser to make it proper JSON.
I will come back and write a tool to properly clean up the mess at some point, but right now I have another approach I'm doing.

How to return a big XML response in C# Web API

I am creating a web api which need to create large XML responses according to various requests. I tried googling but all the answers are about XMLSerializer.
And I tried making XDocument object and returning it using toString() method.
But it's not working properly too. It gives me output like this
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"><root> <someNode>someValue</someNode> </root></string>
Isn't there an easy way to generate XML dynamically and return it.
Instead of generating XML dynamically, Why don't to use collection of class. Make a generic class and assign the data in collection. Send the collection using media header as xml.
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

When do we use XMLSerialization?

I was searching on examples as how to store data in isolated storage. In an example XmlSerializer was used. I have given the code below. Please explain the function and need for Xmlserializer.
XmlSerializer ser = new XmlSerializer(typeof(TravelReportInfo));
ser.Serialize(fs, travelReportInfo);
XmlSerialization is the process of taking an object and representing it as xml. Xml is one of the ideal formats for this since it can describe arbitrary object hierarchies.
One common use case is transfering objects over the web. If you serialize your object to xml you can include it in http requests and responses and deserialize it back to its original object on the other side. All information to reconstruct the object is found in the xml
Bellow you can see an example of a class serialized to xml
public class OrderForm
{
public DateTime OrderDate;
}
<OrderForm>
<OrderDate>12/12/01</OrderDate>
</OrderForm>

Automatically map asmx-provided xml data to POCO object

In my .net code I am consuming a third-party asmx service that provides me data in Xml format. So basically, I am recieving a structure in a form of XmlNode:
<PostcodeEntry>
<Postcode>13542</Postcode>
<Postcodename>Odessa</Postcodename>
</PostcodeEntry>
Currently, to map it to my POCO object I have to manually iterate through a corresponding ChildNode's and retrieve their InnerText value to get the actual data:
var PostCodeNode = entryNode.SelectSingleNode("Postcode");
if (PostCodeNode != null)
{
result.PostCode = PostCodeNode.InnerText;
}
In case I need to map a large info structure, the code grows to a messy code-scroll.
Is there a way I can improve this so I don't have to write the parsing manually? What is the best practice for this?
I believe that you have different options depending on how you get your data and how you like to design your code etc. From your brief description I can think of at least these two:
Create an XML Serializer - for example by marking up your class with Xml Attributes and de-serialize the XML directly as your desired object via the serializer. The disadvantage of this approach is that you will create a strong coupling between your serializer and your business object. Please take a look at something like this: http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization.
Create a proxy object and map your proxy object to your business object. You can create the proxy object either by using a WSDL exposed by the asmx service, or by using the XSD.exe tool or similar (you may need to first generate an XSD based on the XML if the XML is not already described by an XSD). Then you can map the properties of your proxy object to the properties of your business object. This will provide you a more clean separation between the objects, but at the same time it requires more work.
Br. Morten
You can create SoapClient object for WebService, then you can return the Response as List<>. You need to change the Ouput response to List<>.
example Consilder this the webservice to consume, http://xxx.xx.xxx.xxx/CosmosService/Cm_Service.asmx
then add Service Reference in your application, Click On Advanced Button, change the Collection Type System.Collections.GenericList.
then you can Consume WebService Methods as List<> directly like this
CosmosRef.CM_ServiceSoapClient client = new CosmosRef.CM_ServiceSoapClient();
List<CosmosRef.Product> listProduct = client.GetAllProducts("Computers", 1);
dataGrid1.DataContext = listProduct;

Categories