1 /* 2 * Copyright (C) 2017, David Pursehouse <david.pursehouse@gmail.com> and others 3 * 4 * This program and the accompanying materials are made available under the 5 * terms of the Eclipse Distribution License v. 1.0 which is available at 6 * https://www.eclipse.org/org/documents/edl-v10.php. 7 * 8 * SPDX-License-Identifier: BSD-3-Clause 9 */ 10 11 package org.eclipse.jgit.lfs.server.internal; 12 13 import java.io.Reader; 14 15 import com.google.gson.FieldNamingPolicy; 16 import com.google.gson.Gson; 17 import com.google.gson.GsonBuilder; 18 import com.google.gson.JsonIOException; 19 import com.google.gson.JsonSyntaxException; 20 21 /** 22 * Wrapper for {@link com.google.gson.Gson} used by LFS servlets. 23 */ 24 public class LfsGson { 25 private static final Gson gson = new GsonBuilder() 26 .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) 27 .disableHtmlEscaping() 28 .create(); 29 30 /** 31 * Wrapper class only used for serialization of error messages. 32 */ 33 static class Error { 34 String message; 35 36 Error(String m) { 37 this.message = m; 38 } 39 } 40 41 /** 42 * Serializes the specified object into its equivalent Json representation. 43 * 44 * @param src 45 * the object for which Json representation is to be created. If 46 * this is a String, it is wrapped in an instance of 47 * {@link org.eclipse.jgit.lfs.server.internal.LfsGson.Error}. 48 * @param writer 49 * Writer to which the Json representation needs to be written 50 * @throws com.google.gson.JsonIOException 51 * if there was a problem writing to the writer 52 * @see Gson#toJson(Object, Appendable) 53 */ 54 public static void toJson(Object src, Appendable writer) 55 throws JsonIOException { 56 if (src instanceof String) { 57 gson.toJson(new Error((String) src), writer); 58 } else { 59 gson.toJson(src, writer); 60 } 61 } 62 63 /** 64 * Deserializes the Json read from the specified reader into an object of 65 * the specified type. 66 * 67 * @param json 68 * reader producing json from which the object is to be 69 * deserialized 70 * @param classOfT 71 * specified type to deserialize 72 * @return an Object of type T 73 * @throws com.google.gson.JsonIOException 74 * if there was a problem reading from the Reader 75 * @throws com.google.gson.JsonSyntaxException 76 * if json is not a valid representation for an object of type 77 * @see Gson#fromJson(Reader, java.lang.reflect.Type) 78 * @param <T> 79 * a T object. 80 */ 81 public static <T> T fromJson(Reader json, Class<T> classOfT) 82 throws JsonSyntaxException, JsonIOException { 83 return gson.fromJson(json, classOfT); 84 } 85 }