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>
Related
My code here to get data from Wikipedia:
string URL = $"https://en.wikipedia.org/w/api.php?action=query&format=json&list=&titles={query}&redirects=1";
WebRequest wrREQUEST;
wrREQUEST = WebRequest.Create(URL);
wrREQUEST.Proxy = null;
wrREQUEST.Method = "GET";
WebResponse response = wrREQUEST.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
string responseData = streamReader.ReadToEnd();
JObject jsonData = JObject.Parse(responseData);
var jsonQuery = jsonData["query"];
string pageID = (string)jsonQuery;
But I keep getting
Exception thrown: 'System.ArgumentException' in Newtonsoft.Json.dll
and the json data looks like this:
{
"batchcomplete":"",
"query":{
"pages":{
"31717":{
"pageid":31717,
"ns":0,
"title":"United Kingdom"
}
}
}
}
I also want to know since "pages":{"31717":{}} is an ID which I will not know in advance, how can I get that 31717 from enumerating the data?
The error is because you are trying to explicitly convert JObject into a string, which is not possible using conversion, only by using Serilization.
But I understand you actually want the "PageId", which by the json structure, look like you need to take the "first key" from the response.
(Actually there are more ways)
So instead of
string pageID = (string)jsonQuery;
One possible way, will be using this
((JProperty)jsonQuery["pages"].First()).Name
Please find resolution of yout request, it might be possible that some time u will not get the first element value and it will trigger some exception.
Please replace your line :
string pageID = (string)jsonQuery;
with
**var jToken = jsonQuery["pages"].First;
if (jToken != null)
{
string pageID = ((JProperty) jToken).Name;
}**
i hope someone can help me. i'm a very beginner to json but i try to build a programm that loads all the posts from a subreddit trough the json file. I dont want to save it in a class so creating the classes from json is not an option as i found that not every subreddit has the same structure obviously.
as my example i use the /r/wallpaper https://www.reddit.com/r/wallpaper/hot.json?count=25
That is my current code but i always get a null result to dat2 when searchin in the JObject
var json = "";
using (WebClient client = new WebClient())
{
json = client.DownloadString("https://www.reddit.com/r/wallpaper/hot.json?count=25");
JObject data = JObject.Parse(json);
string dat2 = data["url"].Value<string>();
}
How can i easily search for all value trough a key ? So for example i can get all the thumbnail from each post.
I'm using Json.NET.
You need to find the children and loop through them. Each child has its own url.
Sample code:
var json = "";
using (WebClient client = new WebClient())
{
json = client.DownloadString("https://www.reddit.com/r/wallpaper/hot.json?count=25");
JObject data = JObject.Parse(json);
var children = data["data"]["children"];
for (var i = 0; i < children.Count(); i++)
{
Console.WriteLine(children[i]["data"]["url"]);
}
}
The answer of Get OData $metadata in JSON format states that OData cannot return the metadata as JSON by default.
But is it possible then to capture or hook its response for the $metadata URL, and then convert it on the fly to JSON before sending it to the client?
I imagine pseudocode like this:
[HttpGet]
[ODataRoute("$metadata")]
public string GetMetadataAsJson()
{
string xml = GetOdataMetadataAsXML();
string json = ConvertToJson(xml);
return json;
}
I don't know how to implement it correctly, though, in particular I'm not sure how to get the standard OData response as a string, and how to hook the $metadata URL.
Newtonsoft supports the Json part checkout https://www.newtonsoft.com/json/help/html/ConvertXmlToJson.htm
So the actual solution for the Json Part would be quite simple, as soon as you have your XML
[HttpGet]
[ODataRoute("$metadata")]
public string GetMetadataAsJson()
{
string xml = GetOdataMetadataAsXML();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
return json;
}
Also you should probably first check if e.g. a format query is set for example with this code
[HttpGet]
[ODataRoute("$metadata")]
public string GetMetadataAsJson([FromQuery(Name="Format")]string format)
{
string metaResult = GetOdataMetadataAsXML();
if(format.Equals("json",StringComparison.OrdinalIgnoreCase))
{
XmlDocument metaDoc = new XmlDocument();
doc.LoadXml(metaResult);
metaResult = JsonConvert.SerializeXmlNode(doc);
}
return metaResult;
}
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 >();
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);