Gson library when parse string contain special char \u - gson

I have a simple code like that:
JsonParser parser = new JsonParser();
JsonElement element = parser.parse("{\"description\":\"c:\\userDescription.txt\"}");
JsonObject attributes = element.getAsJsonObject();
System.out.println(attributes);
I expect the outout is:
{"description":"c:\userDescription.txt"}
but actually I have the exeption:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: "serD"
Can you help me, what should the input is to get the expect output:
{"description":"c:\userDescription.txt"}

The following Java string is one character long, the \ character:
String s = "\\";
Like Java, JSON uses \ as its escape character. So you need to escape for Java and for JSON. Try this:
JsonElement element = parser.parse("{\"description\":\"c:\\\\userDescription.txt\"}");

Related

double backslash for unicode in Strings when I output map to json using Gson

I am trying to serialize my LinkedHashMap<String,String> to a json file using GSON
what I tried is this:
LinkedHashMap<String, String> resultMap = new LinkedHashMap<>();
resultMap.put("xxxxx","\\u53D1\\u51FA\\u8BE5");
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create;
try (FileWriter fileWriter = new FileWriter("C:\\Users\\xxxxx\\Desktop\\testGson.json")0{
gson.toJson(resultMap, fileWriter);
} catch( IOException e) {
e.printStackTrace();
}
I want the output json value be like \u53D1\u51fa\u8BE5 but for now the output json have double backslashes, basically the unescaped unicode.
How should I do this?
You are storing \\u53D1\\u51FA\\u8BE5 in the map, that is, not the Unicode characters 发 (U+53D1), ... but instead the literal strings \u53D1, \u51FA and \u8BE5. Gson will output these in the JSON string, and escape the \, since otherwise it would change the value of the string (from \u53D1 to 发 and so on).
Unfortunately there is currently no feature to force Gson to use Unicode escapes for non-ASCII characters (in case that is what you wanted), but as shown in this GitHub issue you could provide a custom java.io.Writer which performs the escaping.

Validation fails when passing a file path as Input Argument to Orchestrator API StartJobs

I am trying to use file name path (Ex: C:\Document\Report.txt) as a parameter through uipath orchastrator api. I tried different approach and In each approach I am getting Bad request error "{"message":"Argument Values validation failed.","errorCode":2003,"resourceIds":null}"
Below is my Example code
FileListUploaded ="C\\Documents\\report.txt";
string parameter1 = "{\"startInfo\": {\"ReleaseKey\": \"xxxxx-xxx-xxx-xxx-xxxxxx\"," +
"\"RobotIds\": [xxxxx]," +
"\"JobsCount\": 0," +
"\"InputArguments\": \"{ "+
"\\\"reports_or_other_files\\\": \\\" + FileListUploaded + \\\"}\"}}";
request_startRobot.AddParameter("application/json; charset=utf-16", parameter, ParameterType.RequestBody);
IRestResponse response_startRobot = client_startRobot.Execute(request_startRobot);
That's a bit messy to look at, but it appears you are not quoting and escaping your JSON correctly.
I might suggest building an array and serializing it into JSON to make it easier to read, or using a HEREDOC or string formatting. If you do continue to concatenate your JSON body string together, dump out the results to see how it is coming together.
The final results of the JSON should look something like
{
"startInfo": {
"ReleaseKey":"{{uipath_releaseKey}}",
"Strategy":"JobsCount",
"JobsCount":1,
"InputArguments":"{\"reports_or_other_files\":\"C:\\\\Documents\\\\report.txt\"}"
}
}
With the InputArguments:
Looks like you are missing some quotes
Might need to double escape your backslashes in the FileListUploaded variable
Missing a colon after the C in the path

Writing null values into parquet file with mapper

I am trying to do the following:
String x=null;
Group group = factory.newGroup()
.append("x", x);
context.write(null,group)
With the following scheme:
String writeSchema = "message example {\n" +
"optional binary x;\n" +
"}";<br>
But I get NullPointerException in the append line. Maybe I am missing something in the scheme?
Here the String object itself is null. While writing to the filesystem it tries to get the value of the object which is causing the NullPointerExeception.
String x =null;
System.out.println(x.toString()); // Will cause a NullPointerExeception
Similarly any function call to the object will cause the same.
Try using String x ="null" instead

URL encoding using the new Spring UriComponentsBuilder

I'm attempting to use spring's UriComponentsBuilder to generate some urls for oauth interaction. The query parameters include such entities as callback urls and parameter values with spaces in them.
Attempting to use UriComponentBuilder (because UriUtils is now deprecated)
UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(oauthURL);
urlBuilder.queryParam("client_id", clientId);
urlBuilder.queryParam("redirect_uri", redirectURI);
urlBuilder.queryParam("scope", "test1 test2");
String url = urlBuilder.build(false).encode().toUriString();
Unfortunately, while the space in the scope parameter is successfully replaced with '+', the redirect_uri parameter is not at all url encoded.
E.g,
redirect_uri=https://oauth2-login-demo.appspot.com/code
should have ended up
redirect_uri=https%3A%2F%2Foauth2-login-demo.appspot.com%2Fcode
but was untouched. Diving into the code, specifically org.springframework.web.util.HierarchicalUriComponents.Type.QUERY_PARAM.isAllowed(c) :
if ('=' == c || '+' == c || '&' == c) {
return false;
}
else {
return isPchar(c) || '/' == c || '?' == c;
}
clearly allows ':' and '/' characters, which by gum, it shouldn't. It must be doing some other type of encoding, though for the life of me, I can't imagine what. Am I barking up the wrong tree(s) here?
Thanks
UriComponentsBuilder is encoding your URI in accordance with RFC 3986, with section 3.4 about the 'query' component of a URI being of particular note.
Within the 'query' component, the characters / and : are permitted, and do not need escaping.
To take the / character for example: the 'query' component (which is clearly delimited by unescaped ? and (optionally) # characters), is not hierarchical and the / character has no special meaning. So it doesn't need encoding.
from what I understand, UriComponentsBuilder doesn't encode the query parameters automatically, just the original HttpUrl it's instantiated with. In other words, you still have to explicitly encode:
String redirectURI= "https://oauth2-login-demo.appspot.com/code";
urlBuilder.queryParam("redirect_uri", URLEncoder.encode(redirectURI,"UTF-8" ));
Try to scan the UriComponentsBuilder doc, there is method named build(boolean encoded)
Sample code 1:
UriComponents uriComponents = UriComponentsBuilder.fromPath("/path1/path2").build(true);
Here is my sample code 2:
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("https")
.host("my.host")
.path("/path1/path2").query(parameters).build(true);
URI uri= uriComponents.toUri();
ResponseEntity<MyEntityResponse> responseEntity = restTemplate.exchange(uri,
HttpMethod.GET, entity, typeRef);
I tried all the solutions above until I got it working.
In my example, I was trying to encode the ZonedDateTime format 2022-01-21T10:17:10.228+06:00. The plus sign was a problem.
What solved my issue was encoding the value manually + using URI instead of the string value (both were very important).
Before:
restTemplate.exchange(
UriComponentsBuilder
.queryParam("fromDateTime", "2022-01-21T10:17:10.228+06:00")
.build()
.toUriString(),
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<MyDto>>() {}
);
After:
restTemplate.exchange(
UriComponentsBuilder
.queryParam("fromDateTime", URLEncoder.encode("2022-01-21T10:17:10.228+06:00", StandardCharsets.UTF_8))
.build(true)
.toUri(),
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<MyDto>>() {}
);

c# stringbuilder tostring double quote issue

I have an issue when converting a string from stringbuilder to string.
The issue is similar to this issue but slightly different:
This is my code simplified:
StringBuilder sb = new StringBuilder();
sb.Append("\"");
sb.Append("Hello World");
sb.Append("\"");
string test = sb.ToString();
Now in the debugger the sb value is:
"Hello World"
In the debugger the test string value is changed to:
\"Hello World\"
When returning the test string value back to the browser the velue is STILL escaped:
\"Hello World\"
I have tried using the string replace:
test = test.Replace("\"", "");
no luck, I tried appending the ASCII character instead of \" and I have also tried a different append
sb.Append('"');
All these with no luck. Can somebody maybe point me in the right direction of why I'm still getting the escape character and how to get rid of it.
Thanks and appreciate any input.
Ok it seems that in WCF the stringBuilder automatically adds escape quotes. This means you can not get away from that. Also I was going about this all wrong. I was trying to return a string where I was supposed to return a serialised JSON object.
I'm not seeing the behavior you describe. Escaping double quotes with the backslash should work. The following snippet of code
var sb = new StringBuilder();
sb.Append("Ed says, ");
sb.Append("\"");
sb.Append("Hello");
sb.Append("\"");
Console.WriteLine(sb.ToString());
foreach (char c in sb.ToString()) Console.Write(c + "-");
Console.ReadKey();
produces
Ed says, "Hello"
E-d- -s-a-y-s-,- -"-H-e-l-l-o-"-
If you are getting actual backslash characters in your final display of the string, that may be getting added by something after the StringBuilder and ToString code.
You can use a verbatim string literal "#" before the string, then enter the quotes twice. This removes the use to use escapes in the string sequence :)
StringBuilder sb = new StringBuilder();
sb.Append(#"""");
sb.Append("Hello World");
sb.Append(#"""");
string test = sb.ToString();
This question and answer thread kept on coming up when searching for the solution.
The confusion, for me, was that the Debugger escaping looks exactly the same as the JSON serializer behaviour that was being applied later when I returned the string to a client. So the code at the top of the thread (and my code) worked correctly.
Once I realised that, I converted the piece of code I was working on return an array (string[] in this case) and store that rather than the original string object. Later the JSONResult serializer then dealt with converting the array correctly.

Resources