Example usage for com.google.gson GsonBuilder registerTypeAdapter

List of usage examples for com.google.gson GsonBuilder registerTypeAdapter

Introduction

In this page you can find the example usage for com.google.gson GsonBuilder registerTypeAdapter.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) 

Source Link

Document

Configures Gson for custom serialization or deserialization.

Usage

From source file:concept.tools.Deserializer.java

License:Open Source License

/**
 * @param pathAndFileName//  w  ww  . ja va2  s .  com
 *            path and name of file
 * @param cls
 *            class for which to deserialize.
 * @param <T> which can be any type derived from object.
 * @return instance of type T or null if failed to read JSON file.
 * @throws FileNotFoundException
 *             if file has not been found.
 */
public static <T> T withGsonFromJson(final String pathAndFileName, final Class<T> cls)
        throws FileNotFoundException {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(AbstractMatcher.class, new MatcherSerializer());
    final Gson gson = gsonBuilder.create();

    final FileReader reader = new FileReader(pathAndFileName);
    return gson.fromJson(reader, cls);
}

From source file:concept.tools.Serializer.java

License:Open Source License

/**
 * Serializes hierarchy to a JSON string using gson library.
 *
 * @param object//from   w w w  .j  a v  a 2  s.co m
 *            root object of hierarchy to serialize.
 * @return JSON string for given hierarchy,
 */
public static String withGsonToJson(final Object object) {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(AbstractMatcher.class, new MatcherSerializer());
    final Gson gson = gsonBuilder.create();
    return gson.toJson(object);
}

From source file:cr.ac.una.prograiv.moviestar.controller.CarritoServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  ww  w  .  j  a  v a2 s .c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        //String para guardar el JSON generaro por al libreria GSON
        String json;
        //Se crea el objeto Persona
        Catalogos c = new Catalogos();

        GsonBuilder b = new GsonBuilder();

        Gson gson = b.registerTypeAdapter(Catalogos.class, new CatalogosAdapter()).create();

        //Se crea el objeto de la logica de negocio
        CatalogosBL cBL = new CatalogosBL();

        //Se hace una pausa para ver el modal
        Thread.sleep(1000);

        //**********************************************************************
        //se consulta cual accion se desea realizar
        //**********************************************************************

        String accion = request.getParameter("accion");
        HttpSession sesion = request.getSession();
        switch (accion) {
        case "add": //Una pelicula o serie no deberia poder ser modificada
            c.setCId(Integer.parseInt(request.getParameter("id")));
            c.setCNombre(request.getParameter("nombre"));
            c.setCPrecAlqu(Float.parseFloat(request.getParameter("precioAlq")));
            c.setCPrecComp(Float.parseFloat(request.getParameter("precioCom")));
            synchronized (sesion) {
                List<Catalogos> list = (List<Catalogos>) sesion.getAttribute("car");
                if (list == null) {
                    list = new ArrayList<>();
                    sesion.setAttribute("car", list);
                }
                list.add(c);
                out.print("El elemento se aadi al carrito");
            }
            break;
        case "get":
            List<Catalogos> l = (List<Catalogos>) sesion.getAttribute("car");

            json = new Gson().toJson(l);
            out.print(json);
            break;
        default:
            out.print("E~No se indico la accin que se desea realizar");
            break;
        }

    } catch (NumberFormatException | InterruptedException e) {
        out.print("E~" + e.getMessage());
    }
}

From source file:data.JSONDataInserter.java

License:Open Source License

private static Gson createGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Category.class, new CategoryDeserializer());
    gsonBuilder.registerTypeAdapter(Question.class, new QuestionDeserializer());
    gsonBuilder.registerTypeAdapter(Answer.class, new AnswerDeserializer());
    return gsonBuilder.create();
}

From source file:de.arkraft.jenkins.JenkinsHelper.java

License:Apache License

public static GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();

    builder.registerTypeAdapter(DateTime.class, new JsonDeserializer<DateTime>() {
        @Override/*from  w w w . jav  a 2s.c  o m*/
        public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            // using the correct parser right away should save init time compared to new DateTime(<string>)
            return ISO_8601_WITH_MILLIS.parseDateTime(json.getAsString());
        }
    });

    builder.registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>() {
        @Override
        public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src.toString());
        }
    });

    builder.registerTypeAdapter(Duration.class, new JsonDeserializer() {
        @Override
        public Object deserialize(JsonElement json, Type type,
                JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return Duration.parse("PT" + json.getAsString() + "S");
        }
    });

    builder.registerTypeAdapter(Action.class, new JsonDeserializer<Action>() {
        @Override
        public Action deserialize(JsonElement jsonElement, Type type,
                JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

            JsonObject object = ((JsonObject) jsonElement);
            if (object.has("causes")) {
                JsonElement element = object.get("causes");
                if (element.isJsonArray()) {
                    return jsonDeserializationContext.deserialize(element, Causes.class);
                }
            }
            if (object.has("failCount")) {
                return jsonDeserializationContext.deserialize(object, CountAction.class);
            }
            return null;
        }
    });

    builder.registerTypeAdapter(ChangeSet.class, new JsonDeserializer<ChangeSet>() {
        @Override
        public ChangeSet deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
                throws JsonParseException {
            ChangeSet changeSet = new ChangeSet();
            JsonObject object = (JsonObject) jsonElement;
            if (object.has("items") && object.get("items").isJsonArray()) {
                for (JsonElement element : object.get("items").getAsJsonArray()) {
                    ChangeSet.Change change = context.deserialize(element, ChangeSet.Change.class);
                    changeSet.add(change);
                }
            }
            if (object.has("kind")) {
                changeSet.setKind(object.get("kind").getAsString());
            }
            return changeSet;
        }
    });

    builder.registerTypeAdapter(Duration.class, new JsonSerializer<Duration>() {
        @Override
        public JsonElement serialize(Duration duration, Type type,
                JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(duration.toString().replace("PT", "").replace("S", ""));
        }
    });

    builder.registerTypeAdapter(EditType.class, new JsonDeserializer<EditType>() {
        @Override
        public EditType deserialize(JsonElement jsonElement, Type type,
                JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return EditType.byName(jsonElement.getAsString());
        }
    });

    builder.registerTypeAdapter(HealthIcon.class, new JsonDeserializer<HealthIcon>() {
        @Override
        public HealthIcon deserialize(JsonElement jsonElement, Type type,
                JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return HealthIcon.fromName(jsonElement.toString());
        }
    });

    builder.registerTypeAdapter(Queue.class, new JsonDeserializer<Queue>() {
        @Override
        public Queue deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
                throws JsonParseException {
            Queue queue = new Queue();
            JsonObject jsonObject = (JsonObject) jsonElement;
            if (jsonObject.has("items") && jsonObject.get("items").isJsonArray()) {
                for (JsonElement element : jsonObject.get("items").getAsJsonArray()) {
                    Queue.Item build = context.deserialize(element, Queue.Item.class);
                    queue.add(build);
                }
            }
            return queue;
        }
    });

    builder.registerTypeAdapter(JobCollection.class, new JsonDeserializer<JobCollection>() {
        @Override
        public JobCollection deserialize(JsonElement json, Type type, JsonDeserializationContext context)
                throws JsonParseException {
            JobCollection jobs = new JobCollection();
            JsonObject object = (JsonObject) json;
            if (object.has("jobs") && object.get("jobs").isJsonArray()) {
                for (JsonElement element : object.get("jobs").getAsJsonArray()) {
                    Job job = context.deserialize(element, Job.class);
                    jobs.add(job);
                }
            }
            return jobs;
        }
    });

    builder.registerTypeAdapter(BallColor.class, new JsonDeserializer<BallColor>() {
        @Override
        public BallColor deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext json)
                throws JsonParseException {
            return BallColor.valueOf(jsonElement.getAsString().toUpperCase());
        }
    });

    return builder;
}

From source file:de.bahnhoefe.deutschlands.bahnhofsfotos.BaseApplication.java

License:Open Source License

@Override
public void onCreate() {
    super.onCreate();
    dbAdapter = new BahnhofsDbAdapter(this);
    dbAdapter.open();/*from  w  w w  .  j av a  2 s .c  om*/

    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(HighScore.class, new HighScore.HighScoreDeserializer());
    gson.registerTypeAdapter(License.class, new License.LicenseDeserializer());

    Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.API_START_URL)
            .addConverterFactory(GsonConverterFactory.create(gson.create())).build();

    api = retrofit.create(RSAPI.class);

    preferences = getSharedPreferences(PREF_FILE, MODE_PRIVATE);

    // migrate photo owner preference to boolean
    final Object photoOwner = preferences.getAll().get(getString(R.string.PHOTO_OWNER));
    if (photoOwner instanceof String && "YES".equals(photoOwner)) {
        setPhotoOwner(true);
    }
}

From source file:de.bitsharesmunich.cryptocoincore.steem.SteemTransaction.java

@Override
public String toJsonString() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(SteemTransaction.class, new SteemTransactionSerializer());
    return gsonBuilder.create().toJson(this);
}

From source file:de.dentrassi.pm.maven.ChannelData.java

License:Open Source License

/**
 * Make an appropriate Gson parser to processing ChannelData instances
 *
 * @param pretty// w  w w  .  j  ava2  s .  com
 *            if the gson output should be "pretty printed"
 * @return the new gson instance
 */
public static Gson makeGson(final boolean pretty) {
    final GsonBuilder gb = new GsonBuilder();

    if (pretty) {
        gb.setPrettyPrinting();
    }

    gb.registerTypeAdapter(Node.class, new NodeAdapter());
    gb.registerTypeAdapter(byte[].class, new ByteArrayAdapter());

    return gb.create();
}

From source file:de.elomagic.carafile.share.JsonUtil.java

License:Apache License

/**
 * Creates a {@link Gson} instance inclduing (de)serializer for class {@link Date}.
 *
 * @return/* ww w.  j a v  a  2 s  .c o  m*/
 */
public static Gson createGsonInstance() {
    GsonBuilder gb = new GsonBuilder();
    gb.registerTypeAdapter(Date.class, new DateDeserializer());
    gb.registerTypeAdapter(Date.class, new DateSerializer());
    return gb.create();
}

From source file:de.fzi.fhemapi.server.FHEMConnection.java

License:Apache License

/**
 * Gets a single object from the server. Some methods in fhem do that. The response is 
 * represented by a ResponseObject. /*from w w w  .  ja  va  2  s. c  om*/
 * @param methodName the name of the method
 * @param params the parameters of the call; Mostly a name and some other stuff
 * @param clazz the class type to return, eg. DeviceType.class
 * @return the object.
 */
@SuppressWarnings("unchecked")
public ResponseObject getSingleObject(String methodName, Map<String, String> params,
        @SuppressWarnings("rawtypes") Class clazz) {
    try {
        String jsonObject = callMethod(methodName, params);
        final int lineSize = 200;
        if (jsonObject.length() > lineSize) {
            System.out.println("jsonObject: ");
            String s = jsonObject;
            while (s.length() > lineSize) {
                System.out.println(s.substring(0, lineSize));
                s = s.substring(lineSize);
            }
            System.out.println(s);
        } else {
            System.out.println("jsonObject: " + jsonObject);
        }
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Reading.class, new ReadingDeserializer());
        gsonBuilder.registerTypeAdapter(fhem.class, new FhemElementDeserializer());
        Gson gson = gsonBuilder.create();

        // TODO hier sollte clazz anstelle von DeviceResponse.class verwendet werden
        // sonst funktioniert das nur fuer DeviceResponses
        return gson.fromJson(jsonObject, DeviceResponse.class);
        //return new Gson().fromJson(jsonObject, DeviceResponse.class);
        //            return new Gson().fromJson(jsonObject, clazz);

        //return new ResponseObject();

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}