Reputation: 16354
I am trying to get an array of objects from the server, using JSON.
The server sends me the following string.
"[{\"DealComment\":null,\"DealVotes\":[],\"DealId\":1,\"CompanyId\":1,\"StartDate\":\"2012-12-13T00:00:00\",\"EndDate\":\"2012-12-16T00:00:00\",\"CouponCode\":\"Test Coupon 1\",\"Description\":\"Test Deal Description 1\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 1\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":2,\"CompanyId\":1,\"StartDate\":\"2012-12-16T00:00:00\",\"EndDate\":\"2012-12-17T00:00:00\",\"CouponCode\":\"Test Coupon 2\",\"Description\":\"Test Description 2\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 2\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":3,\"CompanyId\":1,\"StartDate\":\"2012-12-14T00:00:00\",\"EndDate\":\"2012-12-15T00:00:00\",\"CouponCode\":\"Test Code 3\",\"Description\":\"Test Description 3\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 3\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":4,\"CompanyId\":1,\"StartDate\":\"2012-12-12T00:00:00\",\"EndDate\":\"2012-12-13T00:00:00\",\"CouponCode\":\"Test Coupon 4\",\"Description\":\"Test Description 4\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Test Deal 4\"},{\"DealComment\":null,\"DealVotes\":[],\"DealId\":5,\"CompanyId\":2,\"StartDate\":\"2012-12-12T00:00:00\",\"EndDate\":\"2012-12-14T00:00:00\",\"CouponCode\":\"AwD\",\"Description\":\"Very awesome deal!\",\"VoteUp\":null,\"VoteDown\":null,\"ViewCount\":null,\"Title\":\"Awesome Deal 1\"}]"
Now, if you look at the string closely, you would notice that it contains an \"
instead of every "
. The string cannot be formatted to a JSONArray right now. So, I need to replace every occurrence of \"
with "
, which would have a pretty easy task, had \
not been an escape sequence.
I tried using the following code.
String jsonFormattedString = jsonStr.replaceAll("\\", "");
But it gives me the following exception.
12-19 00:35:59.575: W/System.err(444): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_BAD_ESCAPE_SEQUENCE near index 1:
12-19 00:35:59.575: W/System.err(444): \
12-19 00:35:59.575: W/System.err(444): ^
My whole code, in case it is of any use :
public void getAllDealsFromServerJson()
{
String apiUrl = "http://passme.azurewebsites.net/api/TestApi/";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost httpPost = new HttpPost(apiUrl);
json.put("requestType", "getalldeals" );
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
response = client.execute(httpPost);
Log.d("Http Response:", response.toString());
jsonResponse = response.toString();
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonStr = reader.readLine();
Log.d("String Response", jsonStr);
String jsonFormattedString = jsonStr.replaceAll("\\", ""); // gives error
Log.d("Formatted String", jsonFormattedString);
//JSONTokener tokener = new JSONTokener(jsonFormattedString);
/*JSONObject finalResult = new JSONObject(tokener);
Log.d("JSON Response", "" + finalResult.optString("Title"));*/
JSONArray resultArray = new JSONArray(jsonFormattedString);
Log.d("JSON Array Result Length", "" + resultArray.length());
Log.d("JSON Array Result ", "" + resultArray.getJSONObject(0).optInt("DealId"));
}
catch (Exception e)
{
e.printStackTrace();
}
}
Upvotes: 27
Views: 112177
Reputation: 22387
jsonObj.toString()
.replace("\"[", "[").replace("]\"", "]")
.replace("\\\"{", "{").replace("}\\\"", "}")
.replace("\\\\\\\"", "\"")
Upvotes: 1
Reputation: 27476
Actually the correct way would be:
String jsonFormattedString = jsonStr.replace("\\\"", "\"");
You want to replace only \"
with "
, not all \
with nothing (it would eat up your slashes in json strings, if you have ones).
Contrary to popular believe replace(...)
also replaces all occurrences of given string, just like replaceAll(...)
, it just doesn't use regexp so it usually be faster.
Upvotes: 16
Reputation: 20307
Just use:
try {
jsonFormattedString = new JSONTokener(jsonString).nextValue().toString();
} catch (JSONException e) {
e.printStackTrace();
}
See documentation
Upvotes: 12
Reputation: 9546
You can just use:
str.replace("\\","");
replace takes string as param, replaceAll uses RegEx. it may work like this also:
str.replaceAll("\\\\", "");
Upvotes: 6
Reputation: 11042
It looks like your incoming string is doubly JSON encoded. You should decode it, then decode that again.
Here's my best guess as to how you might do that in Java:
JSONArray resultArray = new JSONArray(new JSONString(jsonFormattedString));
I'm assuming here that JSONString
is a type. Your actual solution may vary.
Under normal circumstances, I'd expect a service to give you JSON straight up. It appears that this services is giving you a string (encoded according to the JSON spec) which contains JSON.
It's the difference between the following:
String someJSON = "[0, 1, 2]";
String doublyEncodedJSON = "\"[0, 1, 2]\"";
Notice the extra leading and trailing quotes? That's because the latter is a string of JSON. You'd have to decode it twice to get the actual object.
Upvotes: 5
Reputation: 236004
Try this:
String jsonFormattedString = jsonStr.replaceAll("\\\\", "");
Because the backslash is the escaping character in a regular expression (replaceAll()
receives one as parameter), it has to be escaped, too.
Upvotes: 49