java - How to escape slashes in Gson -
according json specs, escaping "/
" optional.
gson not default, dealing webservice expecting escaped "/
". want send "somestring\\/someotherstring
". ideas on how achieve this?
to make things clearer: if try deserialize "\\/
" gson, send "\\\\/
", not want!
answer: custom serializer
you can write own custom serializer - have created 1 follows rule want /
\\/
if string escaped want stay \\/
, not \\\\/
.
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 new string stringbuilder builder = new stringbuilder(); // first occurrence int index = src.indexof('/'); // lastadded starting @ position 0 int lastadded = 0; while (index >= 0) { // append first part without / builder.append(src.substring(lastadded, index)); // if / doesn't have \ directly in front - add \ if (index - 1 >= 0 && !src.substring(index - 1, index).equals("\\")) { builder.append("\\"); // if @ index 0 add because - it's // first character } else if (index == 0) { builder.append("\\"); } // change last added index lastadded = index; // change index new occurrence of / index = src.indexof('/', index + 1); } // add rest of string builder.append(src.substring(lastadded, src.length())); // return new string return builder.tostring(); } }
this create following string:
"12 /first /second \\/third\\/fourth\\//fifth"`
the output:
"12 \\/first \\/second \\/third\\/fourth\\/\\/fifth"
register custom serializer
than of course need pass serializer gson on setup this:
gson gson = new gsonbuilder().registertypeadapter(string.class, new escapestringserializer()).create(); string json = gson.tojson(yourobject);
downloadable & executable example
you can find answer , exact example in github stackoverflow answers repo:
gson customserializer escape string in special way dominikangerer
Comments
Post a Comment