Reputation: 14556
According to the json specs, escaping "/
" is optional.
Gson does not do it by default, but I am dealing with a webservice which is expecting escaped "/
". So what I want to send is "somestring\\/someotherstring
". Any ideas on how to achieve this?
To make things clearer: if I try to deserialize "\\/
" with Gson, it will send "\\\\/
", which is not what I want!
Upvotes: 3
Views: 4863
Reputation: 6530
You can write your own Custom Serializer - I have created one which follows the rule that you want /
to be \\/
but if the string is already escaped you want it to stay \\/
and not be \\\\/
.
package com.dominikangerer.q29396608;
import java.lang.reflect.Type;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class EscapeStringSerializer implements JsonSerializer<String> {
@Override
public JsonElement serialize(String src, Type typeOfSrc,
JsonSerializationContext context) {
src = createEscapedString(src);
return new JsonPrimitive(src);
}
private String createEscapedString(String src) {
// StringBuilder for the new String
StringBuilder builder = new StringBuilder();
// First occurrence
int index = src.indexOf('/');
// lastAdded starting at position 0
int lastAdded = 0;
while (index >= 0) {
// append first part without a /
builder.append(src.substring(lastAdded, index));
// if / doesn't have a \ directly in front - add a \
if (index - 1 >= 0 && !src.substring(index - 1, index).equals("\\")) {
builder.append("\\");
// if we are at index 0 we also add it because - well it's the
// first character
} else if (index == 0) {
builder.append("\\");
}
// change last added to index
lastAdded = index;
// change index to the new occurrence of the /
index = src.indexOf('/', index + 1);
}
// add the rest of the string
builder.append(src.substring(lastAdded, src.length()));
// return the new String
return builder.toString();
}
}
This will create from the following String:
"12 /first /second \\/third\\/fourth\\//fifth"`
the output:
"12 \\/first \\/second \\/third\\/fourth\\/\\/fifth"
Register your Custom Serializer
Than of course you need to pass this serializer to Gson on Setup like this:
Gson gson = new GsonBuilder().registerTypeAdapter(String.class, new EscapeStringSerializer()).create();
String json = gson.toJson(yourObject);
You can find this answer and the exact example in my github stackoverflow answers repo:
Gson CustomSerializer to escape a String in a special way by DominikAngerer
Upvotes: 3