How to Serialize XML to a JSON object with Json.NET - c#

I can serialize XML to a JSON string like this:
var xml = new XmlDocument();
xml.LoadXml("<person><name>John</name></person>");
string jsonString = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xml, Newtonsoft.Json.Formatting.None);
Response.ContentType = "application/json";
Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(jsonString));
That would give me:
"{\"person\":{\"name\":\"John\"}}"
But how can I serialize it to a JSON object? Like this:
{"person":{"name":"John"}}

Sometimes we just want to make it harder than it is ...
var xml = new XmlDocument();
xml.LoadXml("<person><name>John</name></person>");
Response.ContentType = "application/json";
Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(xml));
What I did wrong was to serialize the XML into a string and then serialize it again.

when you will access data then / automatically does not show .
I am accessing in HTML5 help of AJAX post .
Result is showing
in C# result is showing that "{\"person\":{\"name\":\"John\"}}"
But in HTML5 , it is working fine
{"person":{"name":"John"}}

Related

send list<xmldocument> to wcf, how to do it?

I'm trying to send List to wcf.
i want to send it as json, is there a way ?
when I'm trying to serialize, i get empty string, why ?
public string ImportXml(List<XmlDocument> docs,string token)
{
Account user = GetCurrentUser(token);
string url = string.Format("{0}ImportXml/{1}", ServiceUrl, user.Unumber);
string contentType = "text/json";
x.Serialize(Console.Out, docs);
string jsonReq = _serializer.Serialize(docs);
bool response = false;
HttpRequestHandler handler = new HttpRequestHandler();
string result = handler.HttpPostWithToken(url, jsonReq, contentType, token);
return result ;
}
Each element of the collection docs before sending into WCF is must be serialized into the JSON for example in this way:
string jsonText = JsonConvert.SerializeXmlNode(doc);
where doc is XmlDocument.
Or for Javascript in this way: Converting between XML and JSON
After you get collection of XmlDocument into WCF method try convert each element of entrance collection:
var documents = new List<XmlDocument>();
foreach (var doc in docs)
{
XmlDocument xmlDoc = JsonConvert.DeserializeXmlNode(doc);
documents.Add(xmlDoc);
}
finnally i got list of strings with xml in it.
it is much better, because that way we can work with anyone, and not only C#.
and i moved to newtonsoft instead JSS.
List<string>

How can i send an XML file as an object to some other function

I needed to read(load) one xml file, and send the same file as an object to other function. Here the problem I am facing is, while loading the file, it is converted to XML Object. Now we can get the details of the file by accessing the InnerXML property, where it got converted to String.
How can I get this String object get assigned to an normal Object whose properties are internally similar to this xml?
See the sample:
SearchResponse Response = new SearchResponse();
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\Search_Response.xml");
Object response = new Object();
response = doc.InnerXml;
Response = (SearchResponse)response;
return Response;
Please help me out!
You can achieve this by Serialization.
use Microsoft.Http.HttpClient. This will give you to convert Xml to Object Very easily.
Eg:
SearchResponse Response = new SearchResponse();
var client = new HttpClient();
var httpResponseMessage = client.Get(uri);
Response = httpResponseMessage.Content.ReadAsXmlSerializable<SearchResponse >();

Converting JSON to XML

I trying to convert JSON output into XML. Unfortunately I get this error:
JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.
This is what I up to now created.
string url = string.Format("https://graph.facebook.com/{0}?fields=posts.fields(message)&access_token={1}", user_name, access_token);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
jsonOutput = reader.ReadToEnd();
Console.WriteLine("THIS IS JSON OUTPUT: " + jsonOutput);
}
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonOutput);
Console.WriteLine(doc);
And this is my JSON output:
{"id":"108013515952807","posts":{"data":[{"id":"108013515952807_470186843068804","created_time":"2013-05-14T20:43:28+0000"},{"message":"TEKST","id":"108013515952807_470178529736302","created_time":"2013-05-14T20:22:07+0000"}
How can I solve this problem?
Despite the fact your JSON provided in the question is not complete, you have multiple properties at the top level as indicated by the exception. You have to define the root for it to get valid XML:
var doc = JsonConvert.DeserializeXmlNode(jsonOutput, "root");
EDIT: In order to print out your XML with indentation you can use XDocument class from System.Xml.Linq namespace: XDocument.Parse(doc.InnerXml).
I thought it's worth linking to the Documentation for turning xml to json and the other way around.
The guys are right..
// To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
You can do JSON-to-XML also by using the .NET Framework (System.Runtime.Serialization.Json):
private static XDocument JsonToXml(string jsonString)
{
using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(jsonString)))
{
var quotas = new XmlDictionaryReaderQuotas();
return XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(stream, quotas));
}
}
DeserializeXmlNode returns XDcument.
If needed XNode use FirstNode.
//string jsonOutput="{"id":"108013515952807","posts":{"data":[{"id":"108013515952807_470186843068804","created_time":"2013-05-14T20:43:28+0000"},{"message":"TEKST","id":"108013515952807_470178529736302","created_time":"2013-05-14T20:22:07+0000"}";
var myelement= JsonConvert.DeserializeXmlNode(jsonOutput, "myelement").FirstNode;
Your shared JSON is invalid please go through http://jsonformatter.curiousconcept.com/ and validate your JSON first.
Yourt JSON should look like:
{
"id":"108013515952807",
"posts":{
"data":[
{
"id":"108013515952807_470186843068804",
"created_time":"2013-05-14T20:43:28+0000"
},
{
"message":"TEKST",
"id":"108013515952807_470178529736302",
"created_time":"2013-05-14T20:22:07+0000"
}
]
}
}
Adding on #jwaliszko's answer, converting json to XDocument:
XDocument xml = JsonConvert.DeserializeXNode(json);

Deserialise an xml representation of a string and primitive type - ASP.NET Web API

I am currently implementing a web service with the ASP.net Web API and one of my methods returns a string. The problem is it returns the string like this:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization">Some Resource</string>
This kind of response is what I want, but I don't know how to deserialise it in my web service client.
How would you deserialise any xml representing a string or any primitive datatype?
Thanks!
You can use ReadAsAsync from the System.Net.Http.Formatting.dll. Say
'uri' will get me this data:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
Some Resource
</string>
Then you can use ReadAsAsync to get the string in the XML:
HttpClient client = new HttpClient();
var resp = client.GetAsync(uri).Result;
string value = resp.Content.ReadAsAsync<string>().Result;
(I'm calling .Result directly to demonstrate the use of ReadAsAsync<> here...)
// Convert the raw data into a Stream
string rawData = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Some Resource</string>";
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(rawData));
// User DataContractSerializer to deserialize it
DataContractSerializer serializer = new DataContractSerializer(typeof(string));
string data = (string)serializer.ReadObject(stream);
Console.WriteLine(data);

how to split json format string in order to Deserialize is into .net object?

The subject sounds unclear, but the logic is very simple. I have a returned response data that is in json format. I want to Deserialize it into .net object which I defined already. I use JavaScriptSerializer class Deserialize method, it requires the parameter to be string. Now my response data is in json format, and has more than one roots.
My code is
WebRequest request = WebRequest.Create ("https://xxx.xxxxxx.com/xxxxx");
request.Method = "GET";
request.ContentType = "application/json";
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
The responseText value is
[
{
"webinarKey":5303085652037254656,
"subject":"Test+Webinar+One",
"description":"Test+Webinar+One+Description",
"organizerKey":73563532324,
"times":[{"startTime":"2011-04-26T17:00:00Z","endTime":"2011-04-26T18:00:00Z"}]
},
{
"webinarKey":9068582024170238208,
"name":"Test+Webinar+Two",
"description":"Test Webinar Two Description",
"organizerKey":73563532324,
"times":[{"startTime":"2011-04-26T17:00:00Z","endTime":"2011-04-26T18:00:00Z"}]
}
]
I use following code to deserialize responseText to a .net object that I defined.
JavaScriptSerializer ser = new JavaScriptSerializer();
Webinar w=ser.Deserialize<Webinar>(responseText);
Error comes out says responseText is an array, not string.
Then how to split responseText? I don't think it is appropriate to use string.split() method here.
Your response text is indeed a json array (containing 2 elements), as indicated by the [ and ] characters. Try the following:
Webinar[] w=ser.Deserialize<Webinar[]>(responseText);
Have you tried: List<Webinar> w=ser.Deserialize<List<Webinar>>(responseText);?

Categories

Resources