I have tried using same json file document mentioned by you, the only change that i did is iterating the Json String. Please see the below code.
It works.
try{
List<Document> docList = [Select Id,Type,body, bodyLength, ContentType, Url from Document WHERE ID='01528000003FqHJAA0'];
String jsonStr='';
if(docList.size()>0)
{
Blob b = docList[0].body;
jsonStr = b.toString();
}
Map<String,Object> mapObj = (Map<String,Object>)JSON.deserializeUntyped(jsonStr);
for (String key : mapObj.keySet()){
System.debug('KEY :' + key);
System.debug('Value :' + mapObj.get(key));
}
}catch(Exception exe){
System.debug('EEROR OCCURED : '+exe.getMessage());
}
Answer from Sharan Desai on Stack ExchangeI have tried using same json file document mentioned by you, the only change that i did is iterating the Json String. Please see the below code.
It works.
try{
List<Document> docList = [Select Id,Type,body, bodyLength, ContentType, Url from Document WHERE ID='01528000003FqHJAA0'];
String jsonStr='';
if(docList.size()>0)
{
Blob b = docList[0].body;
jsonStr = b.toString();
}
Map<String,Object> mapObj = (Map<String,Object>)JSON.deserializeUntyped(jsonStr);
for (String key : mapObj.keySet()){
System.debug('KEY :' + key);
System.debug('Value :' + mapObj.get(key));
}
}catch(Exception exe){
System.debug('EEROR OCCURED : '+exe.getMessage());
}
Have you tried escape sequence \u with hex value corresponding to special char ?
\u followed by four-hex-digits
java - How to escape Special Characters in JSON - Stack Overflow
Java escape JSON String? - Stack Overflow
Deal with strings with many special characters like (",',:,;,{,]) etc while doing JSON.parse
java - Deserializing JSON with special characters into a string - Stack Overflow
At the target you can receive the data as text/plain.
Clean it by running :
input.replaceAll("\\p{Cc}", "").
Convert it back to JSON data using any JSON library :
JSONObject inputParams = JSONObject.fromObject(input);
Hope it helps.
In your case it looks like the incoming data is malformed. It must be in an encoding supported by the JSON spec: UTF-8 (default), UTF-16, or UTF-32. So not sure if the following is applicable. Nevertheless...
For most apps I would recommend JSON to Object mapping, which will take care of the escaping. Otherwise, you can call Jackson's (the JSON library used by Mule) String escape method directly.
Here's an example that you can use in MEL. String.valueOf is necessary because quoteAsString returns char[]:
<configuration>
<expression-language>
<import class="org.codehaus.jackson.io.JsonStringEncoder" />
<global-functions>
def quoteJSONString(s) {
String.valueOf(JsonStringEncoder.getInstance().quoteAsString(s))
}
</global-functions>
</expression-language>
</configuration>
I would use a library to create your JSON String for you. Some options are:
- GSON
- Crockford's lib
This will make dealing with escaping much easier. An example (using org.json) would be:
JSONObject obj = new JSONObject();
obj.put("id", userID);
obj.put("type", methoden);
obj.put("msg", msget);
// etc.
final String json = obj.toString(); // <-- JSON string
Apache Commons
If you're already using Apache commons, it provides a static method for this:
StringEscapeUtils.escapeJson("some string")
It converts any string into one that's properly escaped for inclusion in JSON
See the documentation here
I am starting to think why languages like Java, Javascript don't have a support for verbatim string like c# does. I mean, isn't it pita to manually escape all the special characters. How about the case where you don't know beforehand what characters to escape? I have to JSON.parse() a string and my string has tons of such characters. I just want to escape or whatever all of them and convert to json. How do I go about solving this peacefully?
My solution was this: https://stackoverflow.com/a/40558081/370709
function escapeUnicode(str) {
return str.replace(/[^\0-~]/g, function(ch) {
return "\\u" + ("0000" + ch.charCodeAt().toString(16)).slice(-4);
});
}
Problem solved!
JSON.parse needs to get a string which consists only of unicode characters (see Json parsing with unicode characters).
For you the JSON.parse method fails, because your string contains non-unicode characters. If you paste your string into http://jsonparseronline.com/ you will see that it fails because of the character, which is the character the browser displays if the string is not correctly encoded.
So, if you don't have a way to change the endcoding of your string, you won't be able to do this. You can try something like this to change the encoding, but ti give a definite answer you would need to know how your string is encoded in the first place
and the result String is : {\r\n \"xUserPW\": \"dStT0T\"\r\n}
This is not a valid json format. Is webservice returning you json? You cannot simply append \n to received data and convert it.
HttpResponse getResponse = httpclient.execute(httpPost);
HttpEntity returnEntity = getResponse.getEntity();
is = returnEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 128);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
JSONObject jObject = new JSONObject(sb.toString());
should not thow errors
Lets look at the json.org : http://json.org/
in that site the json defined in the side menu i just go along the path thats relevant to your problem:
object -> { members } // each object replaces by { members }
members -> pair // each members replaces by pair
pair -> string : value // and so on ...
string -> "chars"
" chars " -> char chars
char -> any-Unicode-character-
except-"-or-\-or-
control-character \" \\ \/ \b \f \n \r \t \u four-hex-digits
so your json must not begin by control characters, but i checked it and in other json validators it is ok for example in :
http://www.freeformatter.com/json-validator.html
but in json.org it is not. so just remove \r\n from begining and the end.
Given that
I want ... to get [the] Date(1440959400000+0530) part,
I would use
String value = "/Date(1440959400000+0530)/";
int pos1 = value.indexOf("Date(");
if (pos1 > -1) {
int pos2 = value.indexOf(")", pos1);
if (pos2 > pos1) {
value = value.substring(pos1, pos2 + 1);
System.out.println(value);
}
}
Output is
Date(1440959400000+0530)
Note: This works by looking for "Date(" and then the next ")", and it removes everything not between those two patterns.
If you have specific character, ( and ), use substring method to get the value.
String value = "\\/Date(1440959400000+0530)\\/";
int start = value.indexOf("(");
int last = value.lastIndexOf("0");
value = value.substring(start + 1, last + 1);
System.out.println(value); <--- 1440959400000+0530
DataUtil.getDateForUnixDate(value);
I don't know DataUtil.getDateForUnixDate() method, but take care of + character because of it is not number string.
Update
To remove / character use replace method.
String value = "/Date(1440959400000+0530)/";
value = value.replace("/", "");
System.out.println(value);
output
Date(1440959400000+0530)