Gson - 자동 따옴표(")가 이스케이프됩니까?
Java EE 서버에서 GSON을 사용하여 뷰에 json을 제공하고 있습니다.어떤 오브젝트에서는 어떤 것이든 포함할 수 있는 긴 텍스트가 있습니다('참 좋은 뉴스' 등).
디폴트로는 GSON은 이중 따옴표를 피해가지 않기 때문에 유효한 JSON을 생성하지 않는 것으로 알고 있습니다.
이것을 하는 좋은 방법이 있을까요?
당신의 질문을 이해하지 못할 수도 있지만, 설정이나 변경 없이 GSON에게 Strings를 따옴표로 처리하도록 할 수 있었습니다.
import com.google.gson.Gson;
public class GSONTest {
public String value;
public static void main(String[] args) {
Gson g = new Gson();
GSONTest gt = new GSONTest();
gt.value = "This is a \"test\" of quoted strings";
System.out.println("String: " + gt.value);
System.out.println("JSON: " + g.toJson(gt));
}
}
출력:
String: This is a "test" of quoted strings
JSON: {"value":"This is a \"test\" of quoted strings"}
뭘 물어보는 건지 이해가 안 가는 것 같은데?
DisableHtml excape와 함께 setPrettyPrinting을 사용해 보십시오.
import com.google.gson.Gson;
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonArray.toString());
System.out.println( gson.toJson(je));
다음은 샘플 GSON 코드입니다.
final JsonObject obj = new JsonObject();
obj.addProperty("foo", "b\"a\"r");
System.out.println(obj.toString());
출력은 다음과 같습니다.
{"foo":"b"a"r"}
(필요한 대로)
그래서 당신이 뭔가 잘못하고 있거나 오래된 버전의 GSON을 사용하고 있거나 둘 중 하나입니다.암호를 좀 보여줘야 하지 않을까요?
그것이 내가 그것을 해결하기 위해 한 일이다.
private final Gson mGson;
{
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(String.class, new EscapeStringSerializer());
mGson = builder.create();
}
private static class EscapeStringSerializer implements JsonSerializer<String> {
@Override
public JsonElement serialize(String s, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(escapeJS(s));
}
public static String escapeJS(String string) {
String escapes[][] = new String[][]{
{"\\", "\\\\"},
{"\"", "\\\""},
{"\n", "\\n"},
{"\r", "\\r"},
{"\b", "\\b"},
{"\f", "\\f"},
{"\t", "\\t"}
};
for (String[] esc : escapes) {
string = string.replace(esc[0], esc[1]);
}
return string;
}
}
언급URL : https://stackoverflow.com/questions/7258858/gson-automatic-quote-escaping
'programing' 카테고리의 다른 글
| Oracle 데이터베이스를 사용하여 HQL 쿼리에서 현재 날짜를 사용하려면 어떻게 해야 합니까? (0) | 2023.03.21 |
|---|---|
| 사용자 지정 게시 유형의 분류법 값을 가져오는 방법 (0) | 2023.03.21 |
| 액션 리덕스 후 리액트라우터 리다이렉트 (0) | 2023.03.21 |
| 주식 시세 API? (0) | 2023.03.21 |
| SID가 Oracle tnsnames.ora의 서비스 이름과 어떻게 다른지 (0) | 2023.03.21 |