2012年3月24日土曜日

Return json from xml document

I am trying to return a json object from an XML docuement, but the returned object is not in json format. What am i misisng?

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, XmlSerializeString:=False)> _
PublicFunction GetFormObject( _
ByVal strFileLocAsString)As XmlDocument
Try
Dim xmlDocAsNew XmlDocument
xmlDoc.Load(strFileLoc)
Return xmlDoc
Catch allExceptionsAs Exception
MsgBox(HttpUtility.HtmlEncode(allExceptions.Message))
ReturnNothing
EndTry
EndFunction

TIA

Is the XmlDocument class marked as serializable? It needs to be in order to be remoted by JSON.


Hi Scott,

How does one mask an xml document as serializable?

Ron Tornambe


Hi,

I am not sure, but here may be the answer:http://forums.asp.net/p/1054378/1496599.aspx

I am not sure, did you try to specify content-type in request?

Content-Type: application/json

Here the request generated by AJAX.NET Beta 2 proxy, see 'js' before method name:

POST /Source/service.asmx/js/UpdateChat HTTP/1.1
Host: localhost:1123
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.8) Gecko/20061025 Firefox/1.5.0.8
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Content-Type: application/json
Content-Length: 50
Cookie: ASP.NET_SessionId=qpspnn45mgxzlp20xdj0dvng; .SLCVISITOR=200529225
Pragma: no-cache
Cache-Control: no-cache

{"a":246144119,"v":200529225,"n":18,"z":-1,"m":[]}

Thankfomine for providing the answer.

Best Regards


You can use theNewtonsoft.Json libary。

like this:

[WebMethod]
[ScriptMethod]
public string GetData()
{
XmlDataDocument doc =new System.Xml.XmlDataDocument();
doc.LoadXml("/test.xml");

using (StringWriter sw =new StringWriter())
{
using (JsonWriter jsonWriter =new JsonWriter(sw))
{
jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;

JsonSerializer jsonSerializer =new JsonSerializer();
jsonSerializer.Converters.Add(new XmlNodeConverter());

jsonSerializer.Serialize(jsonWriter, doc);
}
return sw.ToString();
}

}

0 件のコメント:

コメントを投稿