Today I've seen an interesting question on the Silverlight forum. The question was: how to change the MaxJsonLenght property of the JavaScriptSerializer object that is used on the serialization of the objects that are passed to the web service?
Answer: well, you need to use the BrowserHttpWebRequest object and create a custom JavaScriptSerializer object. Here's a quick example. Lets start by creating a custom class that is used to return the response of an asmx web service:
public class Test
{
private string _nome;
private string _morada;
public string Nome
{
get { return _nome; }
set { _nome = value; }
}
public string Morada
{
get { return _morada; }
set { _morada = value;}
}
}
Now, the simple web service:
[WebMethod]
[ScriptMethod]
public Test HelloWorld(string info) {
Test t = new Test();
t.Nome = "LKLLL"
t.Morada = info;
return t;
}
Pretty simple stuff...Now, the interesting stuff: the code you need to use to call the web service:
Test ret;
string path = "WebService.asmx/HelloWorld"
using (BrowserHttpWebRequest request =
new BrowserHttpWebRequest(new Uri(path, UriKind.Relative)))
{
request.ContentType = "application/json"
request.Method = "POST"
HttpWebResponse response = null;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
StringBuilder str = new StringBuilder();
str.Append("{");
str.Append("/"info/":");
JavaScriptSerializer converter = new JavaScriptSerializer();
converter.Serialize("address", str);
str.Append("}");
writer.Write(str.ToString());
writer.Flush();
response = request.GetResponse();
}
if (response.StatusCode != HttpStatusCode.OK
{
//check for error and inform user
}
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
JavaScriptSerializer converter = new JavaScriptSerializer();
string json = reader.ReadToEnd();
ret = converter.Deserialize<Test>(json);
if (ret != null)
{
Debug.WriteLine(ret.Nome);
Debug.WriteLine(ret.Morada);
}
else
{
Debug.WriteLine("ret is null");
}
}
}
Important things to retain from the demo sample:
- Don't forget to add the name of the method you're calling to the url;
- When you're using JSON as the serialization format, you must set the content type to application/json;
- I really didn't need to use the serializer to serialize the string; i could simply add it to the string builder but I've opted for using the serializer for demonstrating purposes;
- You really need to get a reference to the response from within the StreamWriter using block;
- Deserializing the return result is easy: you just need to get the JSON string and pass it to the generic Deserialize method.