I am trying to take a string as input from rest client and return json with alternate chars. However, some chars are missing from the string when it returns. On console, all the chars are getting printed.
@Path("/person")
public class PersonResource {
@GET
@Produces("application/json")
@Path("/{userid}")
public Response getJson(@PathParam("userid") String userId) {
return Response.ok(test(userId)).build();
}
public String test(String userId) {
if (userId.length() == 0) {
System.out.println("Enter User name");
}
System.out.println(userId);
char[] c = userId.toCharArray();
userId = "";
for (int i = 0; i < c.length; i=i+2) {
System.out.println(Character.toString(c[i]) + " " + i );
if ((int) c[i] > 127) {
return "invalid chars";
} else if (c[i] % 2 == 0) {
userId = userId + Character.toString(c[i]);
}
}
The request from REST client is
http://localhost:8084/JSONProjectTest/api/person/HelloWorld
and
REST Client returns Hll.json
On console, the following prints:
HelloWorld
H 0
l 2
o 4
o 6
l 8
I tried changing the decimal of chars, but nothing comes up.
You're not only skipping alternate characters - you're also skipping characters whose UTF-16 code unit isn't even:
if (c[i] % 2 == 0)
That rules out 'o' (U+006F) twice, which is why you're getting "Hll" instead of "Hlool".
It's not clear why you've got that if
statement at all, but it looks like you shouldn't have it. (I'd also get rid of all the calls to Character.toString()
and use a StringBuilder
instead of repeated string concatenation, but that's a different matter.)
See more on this question at Stackoverflow