public static void main(String[] args) throws IOException { // init class Place place = new Place(); place.setName("World"); Human human = new Human(); human.setMessage("Hi"); human.setPlace(place); // convert to json String jsonString = new Genson().serialize(human); System.out.println("json " + jsonString); //print "json {"message":"Hi","place":{"name":"World"}}" // convert from json Human newHuman = new Genson().deserialize(jsonString, Human.class); newHuman.say(); // print "Hi , World!" }
/** * Deserializes the incoming json stream into an instance of T. * Genson did not create the instance of InputStream so it will not be closed. */ public <T> T deserialize(InputStream input, GenericType<T> toType) { return deserialize(toType, createReader(input), new Context(this)); }
// tell genson to enable polymorphic types support Genson genson = new Genson.Builder().setWithClassMetadata(true).create(); // json value will be {"@class":"mypackage.LoginRequest", ... other properties ...} String json = genson.serialize(someRequest); // the value of @class property will be used to detect that the concrete type is LoginRequest Request request = genson.deserialize(json, Request.class);
/** * Serializes this object to the passed Writer, as Genson did not instantiate it, you are * responsible of calling close on it. */ public void serialize(Object object, Writer writer) { ObjectWriter objectWriter = createWriter(writer); if (object == null) serializeNull(objectWriter); else serialize(object, object.getClass(), objectWriter, new Context(this)); }
Genson genson = new Genson(); Filter[] filters = genson.deserialize(json, Filter[].class); // or if you need a list List<Filter> filters = genson.deserialize(json, new GenericType<List<Filter>>(){});
InputStream instream = entity.getContent(); Genson genson = new Genson(); ObjectReader reader = genson.createReader(instream); DeserializeIntoThisClass myObject = genson.deserialize(DeserializeIntoThisClass.class, reader, new Context(genson)); // and now you can work with this object and store it in a database if you want
// renames all "fieldOfName" to "toName", excludes from serialization // and deserialization fields named "fieldNamed" and declared in DefinedInClass // and uses fields with all visibility (protected, private, etc) Genson genson = new Genson.Builder().rename("fieldOfName", "toName") .exclude("fieldNamed", DefinedInClass.class) .setFieldFilter(VisibilityFilter.ALL) .create(); genson.serialize(myObject);
public void writeTo(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { Genson genson = getInstance(type); String charset = mediaType.getParameters().get("charset"); if (charset == null) charset = "UTF-8"; if (!charset.equalsIgnoreCase("UTF-8") && !charset.equalsIgnoreCase("UTF-16BE") && !charset.equalsIgnoreCase("UTF-16LE") && !charset.equalsIgnoreCase("UTF-32BE") && !charset.equalsIgnoreCase("UTF-32LE")) throw new UnsupportedEncodingException("JSON spec allows only UTF-8/16/32 encodings."); ObjectWriter writer = genson.createWriter(new OutputStreamWriter(entityStream, charset)); try { genson.serialize(t, rawIfNullGenericType(type, genericType), writer, createContext(annotations, genson)); writer.flush(); } catch (JsonBindingException e) { throw new WebApplicationException(e); } catch (JsonStreamException jse) { throw new WebApplicationException(jse); } }
@Override public Converter<Interval> create(Type type, Genson genson) { return new IntervalConverter(genson.<DateTime>provideConverter(DateTime.class)); } }
class AndroidURIDeserializer implements Deserializer<Uri> { public Uri deserialize(ObjectReader reader, Context ctx) throws TransformationException, IOException { return Uri.parse(reader.valueAsString()); } } Genson genson = new Genson.Builder().withDeserializers(new AndroidURIDeserializer()).create(); Intent pojo = genson.deserialize(json, Intent.class);
String jsonAsString = "{ \"name\":\"Foo\" }"; Map<String, String> map = (new Genson()).deserialize(jsonAsString, Map.class); String path = "..."; ClientResponse resp = Client.create().resource(path) .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .put(ClientResponse.class, map);
/** * Serializes this object and writes its representation to writer. As you are providing the * writer instance you also must ensure to call flush and close on it when you are done. * * @param object * @param writer into which to write the serialized object. * @throws com.owlike.genson.JsonBindingException * @throws JsonStreamException */ public void serialize(Object object, ObjectWriter writer, Context ctx) { if (object == null) serializeNull(writer); else serialize(object, object.getClass(), writer, ctx); }
/** * @see #deserializeValues(com.owlike.genson.stream.ObjectReader, GenericType) */ public <T> Iterator<T> deserializeValues(final InputStream is, final Class<T> type) { return deserializeValues(createReader(is), GenericType.of(type)); }
/** * @see #deserializeInto(com.owlike.genson.stream.ObjectReader, Object, Context) */ public <T> T deserializeInto(byte[] jsonBytes, T object) { return deserializeInto(createReader(jsonBytes), object, new Context(this)); }
public T deserialize(ObjectReader reader, Context ctx) throws Exception { if (ValueType.OBJECT.equals(reader.getValueType())) { String className = reader.nextObjectMetadata().metadata("class"); if (className != null) { try { Class<?> classFromMetadata = ctx.genson.classFor(className); if (!classFromMetadata.equals(tClass)) { Converter<T> deser = ctx.genson.provideConverter(classFromMetadata); return deser.deserialize(reader, ctx); } } catch (ClassNotFoundException e) { throw new JsonBindingException( "Could not use @class metadata, no such class: " + className); } } } return wrapped.deserialize(reader, ctx); } }
/** * Creates a new ObjectReader with this Genson instance configuration and tries to detect the encoding * from the stream content. */ public ObjectReader createReader(InputStream is) { try { return createReader(readerFactory.createReader(is)); } catch (IOException e) { throw new JsonStreamException("Failed to detect encoding.", e); } }
/** * Creates a new ObjectWriter with this Genson instance configuration. */ public ObjectWriter createWriter(OutputStream os, Charset charset) { return createWriter(new OutputStreamWriter(os, charset)); }
/** * Deserializes the incoming json stream into an instance of T. * Genson did not create the instance of Reader so it will not be closed */ public <T> T deserialize(Reader reader, GenericType<T> toType) { return deserialize(toType, createReader(reader), new Context(this)); }
Genson genson = new Genson.Builder() // enables polymorphic types support .setWithClassMetadata(true) // enables no arg support .setWithDebugInfoPropertyNameResolver(true) .create(); // will look like: [{"@class": "com.xxx.SomeConcreteClass", ...}, {"@class": "com.XXX.OtherClass"}] String json = genson.serialize(getListOfAs()); List<A> listOfA = genson.deserialize(json, new GenericType<List<A>>() {});