I try to serialize some webservice parameters using Gson and I get a strange error:
11-03 00:56:43.088: **.helpers.JsonServer(620): Result data:
{"Message":"Error during serialization or deserialization using the
JSON JavaScriptSerializer. The length of the string exceeds the value
set on the maxJsonLength property.\r\nParameter name:
input","StackTrace":" at
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer
serializer, String input, Type type, Int32 depthLimit)\r\n at
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String
input)\r\n at
System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
context, WebServiceMethodData
methodData)","ExceptionType":"System.ArgumentException"}
The parameteres I try to serialize are some strings and numbers, but the issue is when I have a big string (a base64 image) as parameter.
I didn't find a way to increase the depthLimit in Gson object. Any idea?
my code looks like this:
Gson gson = new Gson();
httpPost.setEntity(new StringEntity(gson.toJson(parameters), "utf-8")); //here I get the error
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
parameters is a Hashtable. One of the items in this hash is a big (more than 600k chars) string - the base64 image. This image can be bigger some time - more than 1M.
Question:
How to increase that limit
I just found that the error is not from Android, but from web service. The webservice, .Net, has some limits.
Just in case if someone is interested in how to fix this, set in web.config file:
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="999999999"/>
</webServices>
</scripting>
</system.web.extensions>
The Gson works perfect!
Related
I have a Json String like below
["Monday","Tueday","wednesday","Thuesday","Friday","Saturday"]
What I want to do is send this Json String to a web server using the android studio volley library.
SO I keep getting this error
com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
The string cannot be converted to JsonArray.
So I have 2 questions I need help with.
My first is how to convert string to JsonArray. For example below String.
["Monday","Tueday","wednesday","Thuesday","Friday","Saturday"]
My second question is about passing this Jason Array (once we create) to a web server. I was researching about the Hashmap but I don't know how to send the JsonArray in Hashmap.
I had a go with below code, but it did not work.
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
I don't know how to send JsaonArray in hashmap.
So Overall, I would like to send this above string to web server.
Supose that the name of string is myString.
rString = myString.replace('[','');
rString = rString.replace(']','');
rString = rString.replace('"','');
String split[] = rString.split(',').
Now you have an array called split with every position is a day.
Edit: This is for frist question
Use that
JSONArray yourJsonArray = JSONArray.fromObject(yourJson);
Answer to first question:
I think it's not the exact response from the server, and there's a HTML <br> tag in the response.
because the line Value <br of type java.lang.String cannot be... clearly contains string <br, try replacing the HTML tags and/or decoding/unescaping the HTML tags to plain text, AND then you can convert that plain JSON text to JSONArray.
this snippet might help you out with decoding the response:
String parsedReponse = Html.fromHtml(serverResponse).toString()
if (parsedReponse != null) parsedReponse = parsedReponse.trim();
Answer to second question:
check out OkHttp3 and Retrofit libraries, they're pretty popular and amazing.
those can help you send POST data to your server
hope that helped you :)
I'm sending string below from Android to web service using volley request
params.put("data", objData.toString());
objData.toString() -->
{"report_time":1413876429,"device_id":"13d404d1b3a38ffc","ads_info":"[{\"play_count\":\"26\",\"ad_id\":\"21\"},{\"play_count\":\"58\",\"ad_id\":\"37\"},{\"play_count\":\"14\",\"ad_id\":\"40\"}]"}
Server not accepting it due the \"
How to remove \ keeping the json correct ""
You are not using the web service correctly.
Possibly the service expects to see a JSON array instead of a string containing JSON. Assuming params is a JSONObject and objData is a JSONArray, use params.put("data", objData) instead of the toString() version you have now.
Escaping the double quotes with backslashes is the only way to do this in java.
One other option would be to put the String into some kind of text file that you would then read at runtime.
I need to decode a json response sent from php in android.
JSON Response
{"VehicleNumber":"1234FB14","Make":"BMW","Model":"X5","Type":"Car","Color":"Black","EngineCapacity":"1800cc","Fuel":"Diesel","DateOfReg":"31-Dec-2013","OwnerNIC":"B1234567890123","serviceArray":[[{"VehicleNumber":"1234FB14","DateOfService":"07-march-2014","Mileage":"1800","Description":"tponggshmbch"}],[{"VehicleNumber":"1234FB14","DateOfService":"07-march-2014","Mileage":"1900","Description":"tponggshmbch"}]]}
The response consists of values for their respective keys and I can retrieve these value by just calling getString(key) in java. {key:value,2D Array[][]}
The problem is that I can't decode the 2D Array being passed here. I get it in a string format in java and if I display it in my android app I can view this:
[[{"VehicleNumber":"1234FB14","DateOfService":"07-march-2014","Mileage":"1800","Description":"tponggshmbch"}],[{"VehicleNumber":"1234FB14","DateOfService":"07-march-2014","Mileage":"1900","Description":"tponggshmbch"}]]
But i need to retrieve all the value from the 2D array.
Any help please.
If Your json is quite big I recommend using gson or Jackson libraries.
I am sending json object to server, My url having json object.Json object having special characters,how to encoding special characters in android, please help me.Thanks in advance.
Use UrlEncode.encode(yourstring, "UTF-8");
If I understood you, you want to send a json object using the url itself (that is, as a parameter). If security doesn't matter you (it will be visible), you could just encode using [Base64][1].
You should probably play with your json object to convert it to a byte[], called jsonbytes, for instance, then use Base64.encodeToString(jsonbytes, Base64.URL_SAFE) and sending this as a parameter.
Your server then should convert this Base64 encoded string into a json object, which tends to be straightforward if you're using PHP:
$jsonString = base64_decode($_GET['json']);
$json = json_decode($jsonString, TRUE);
This will give you an associative array in PHP. If you just want the json string, skip the last step.
I have a .Net WCF Rest service returning Json to be consumed by an Android app.
In debug, the WCF service correctly has the return value (Json) as:
{"BaseLoyaltyPoints":1480,"BonusLoyaltyPoints":0,"BrandId":1414, [etc...] }
Also in debug, when it returns to Notepad, the return value has changed to:
{\"BaseLoyaltyPoints\":1480,\"BonusLoyaltyPoints\":0,\"BrandId\":1414, [etc...] }
And when it gets to my Android app, it has become:
{\\"BaseLoyaltyPoints\\":1480,\\"BonusLoyaltyPoints\\":0,\\"BrandId\\":1414, [etc...] }
This is the boilerplate code I am using to serialize the Json:
Dim stream1 As MemoryStream = New MemoryStream
Dim ser As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(FullProduct))
ser.WriteObject(stream1, Me)
Dim _json As String = Encoding.UTF8.GetString(stream1.ToArray())
stream1.Close()
The Android code to get the Json is:
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(getString(R.string.CONST_RestService) + "/json/Product/" + productID);
ResponseHandler<String> handler = new BasicResponseHandler();
result = httpclient.execute(request, handler);
jObject = new JSONObject(result);
What's going on?
Thanks
Dave
The JSON Data needs to be an evaluable JavaScript String - the " character needs to be escaped to \" (the character " as opposed to the String limitor "), and the \ in that expression needs to be escaped as well (because \ also is a special character). So it has been that string all along, it was just printed differently everytime.
Take this JavaScript for an example:
object = JSON.parse("{\"hello\":\"World\"}");
alert(object.hello);
The following is more of a guess than actual knowledge, because I do not know how exactly the classes you used behave, but I think that it's about right.
As you can see, the " characters need to be escaped to \", so your .NET JSON serializer does just that. Everything is fine, interpreting this as JS would work as expected.
Now what is probably going on is that your JSONObject constructor does not expect Strings to be already properly escaped, so it does that itself. To clarify: When you say "with one escape character", you probably mean something like this:
String workingJSONString = "{\"Hello\":\"World\"}"
right? The problem here is that Java has the same escaping rules as JavaScript - this is not what you get from your HTTPRequest, what you get is
String youGotThis = "{\\\"Hello\\\":\\\"World\\\"}"
Because there are literal backslashes in your String, and those need to be escaped as well. I am pretty certain that that is what is going on, and you'd probably either have to tell your .NET JSON serializer not to apply escape rules or find something that constructs a JSONObject from a properly escaped JSON string - or remove the unnecessary escapes yourself.
I hope this helped - but again, I am not fully certain so you should just check out if it actually behaves as I said.