Giter Club home page Giter Club logo

genson's Introduction

Build Status

Genson

Join the chat at https://gitter.im/owlike/genson

Genson is a complete json <-> java conversion library, providing full databinding, streaming and much more.

Gensons main strengths?

  • Easy to use and just works!
  • Its modular and configurable architecture.
  • Speed and controlled small memory foot print making it scale.

Online Documentation

Checkout our new website - http://genson.io.

The old website at http://code.google.com/p/genson/, hosts the documentation and javadoc until release 0.99 inclusive. But starting with 1.0 everything has been moved to github and the new website.

Motivation

Why create another Json databinding library for Java? Many libraries lack either important features or the flexibility to add new ones. As Genson is being developed with such issues in mind, it is easily customizable with support for user extentions, and it includes many useful features out-of-the-box.

Features you will like

  • Easy to use, fast, highly configurable, lightweight and all that into a single small jar!
  • Full databinding and streaming support for efficient read/write
  • Support for polymorphic types (able to deserialize to an unknown type)
  • Does not require a default no arg constructor and really passes the values not just null, encouraging immutability. It can even be used with factory methods instead of constructors!
  • Full support for generic types
  • Easy to filter/include properties without requiring the use of annotations or mixins
  • Genson provides a complete implementation of JSR 353
  • Starting with Genson 0.95 JAXB annotations and types are supported!
  • Automatic support for JSON in JAX-RS implementations
  • Serialization and Deserialization of maps with complex keys

Goals

  • Be as much extensible as possible by allowing users to add new features in a clean and easy way. Genson applies the philosophy that "We can not think of every use case, so give to users the ability to do it by them self in a easy way".
  • Provide an easy to use API.
  • Try to be as fast and scalable or even faster than the most performant librairies.
  • Full support of Java generics.
  • Provide the ability to work with classes of which you don't have the source code.
  • Provide an efficient streaming API.

Download

Genson is provided as an all-in-one solution but also natively supports a few extensions and integrations with other libraries such as JAX-RS implementations, Spring, Joda time, and Scala. These libraries are not included in Genson and won't be pulled transitively if you are using maven (they are marked as optional).

You can download Genson manually from maven central or add the dependency to your pom if you use Maven.

<dependency>
  <groupId>com.owlike</groupId>
  <artifactId>genson</artifactId>
  <version>{{latest_version}}</version>
</dependency>

You can also build it from the sources using Maven.

POJO databinding

The main entry point in Genson library is the Genson class. It provides methods to serialize Java objects to JSON and deserialize JSON streams to Java objects. Instances of Genson are immutable and thread safe, you should reuse them. In general the recommended way is to have a single instance per configuration type.

The common way to use Genson is to read JSON and map it to some POJO and vice versa, read the POJO and write JSON.

Genson genson = new Genson();

// read from a String, byte array, input stream or reader
Person person = genson.deserialize("{\"age\":28,\"name\":\"Foo\"}", Person.class);

String json = genson.serialize(person);
// or produce a byte array
byte[] jsonBytes = genson.serializeBytes(person);
// or serialize to a output stream or writer
genson.serialize(person, outputStream);

public class Person {
  public String name;
  public int age;
}

Java collections

But you can also work with standard Java collections such as Map and Lists. If you don't tell Genson what type to use, it will deserialize JSON Arrays to Java List and JSON Objects to Map, numbers to Long and Double.

Using Java standard types instead of POJO can be a easy way to start learning JSON. In that case you will deal only with List, Map, Long, Double, String, Boolean and null.

// will be deserialized to a list of maps
List<Object> persons = genson.deserialize("[{\"age\":28,\"name\":\"Foo\"}]", List.class);
// will produce same result as
Object persons = genson.deserialize("[{\"age\":28,\"name\":\"Foo\"}]", Object.class);

Instead of using the previous Person class we can use a Map. By default if you don't specify the type of the keys, Genson will deserialize to String and serialize using toString method of the key.

Map<String, Object> person = new HashMap<String, Object>() {{
  put("name", "Foo");
  put("age", 28);
}};

// {"age":28,"name":"Foo"}
String singlePersonJson = genson.serialize(person);
// will contain a long for the age and a String for the name
Map<String, Object> map = genson.deserialize(singlePersonJson, Map.class);

Deserialize generic types

You can also deserialize to generic types such as a list of Pojos.

String json = "[{\"age\":28,\"name\":\"Foo\"}]";

List<Person> persons = genson.deserialize(json, new GenericType<List<Person>>(){});

// or lets say we want to use something else than String as the keys of our Map.
Map<Integer, Object> map = genson.deserialize(
  "{\"1\":28, \"2\":\"Foo\"}",
  new GenericType<Map<Integer, Object>>(){}
);

Note in the previous example we defined the keys (1, 2) as json strings. JSON specification allows only strings as object property names, but Genson allows to map this keys to some - limited - other types.

Customizing Genson

If the default configuration of Genson does not fit your needs you can customize it via the GensonBuilder. For example to enable indentation of the output, serialize all objects using their runtime type and deserialize to classes that don't provide a default no argument constructor can be achieved with following configuration.

Genson genson = new GensonBuilder()
  .useIndentation(true)
  .useRuntimeType(true)
  .useConstructorWithArguments(true)
  .create();

You are ready to rock the JSON! :)

Copyright and license

Copyright 2011-2014 Genson - Cepoi Eugen

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

genson's People

Contributors

armageddon- avatar aseovic avatar azukovskij avatar chenzhang22 avatar choss avatar cvakiitho avatar dependabot[bot] avatar dylan-chong avatar eugencepoi avatar gitter-badger avatar jessecrossley avatar lennartj avatar mykelalvis avatar nicky9door avatar rbromley10 avatar rovak avatar simenrokaas avatar softwareresearchwork avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

genson's Issues

GWT support?

I am always looking for nice libs to use on the server and client side with GWT. GWT simply means, don't use classes on the client side that contain unsupported JRE parts. The list is here: http://www.gwtproject.org/doc/latest/RefJreEmulation.html e.g. there a no streams/writers/readers. The client side would also need JSON creation and reading, I guess.

Be more permissive with metadata position in the json stream

Was expecting it to happen at a moment ... see.

This could be solved by using a marker to indicate that a class should have its metadata ser/de, then read the json for this object in an intermediary structure, extract the metadata, then do the databinding part.

Genson JaxbBundle not utilizing XmlJavaTypeAdapter properly

Genson chokes when trying to write out my java.util.Calendar dates because the JaxbBeanPropertyFactory.getType() method doesn't check to see if the AccessibleObject has an XmlJavaTypeAdapter in order to ensure that the XmlElement type will be assignable. The method works if we simply check that the annotation is non-null:

private Type getType(AccessibleObject object, Type objectType, Type contextType) {
  XmlElement el = object.getAnnotation(XmlElement.class);
  if (el != null && el.type() != XmlElement.DEFAULT.class) {
    if (!TypeUtil.getRawClass(objectType).isAssignableFrom(el.type())) {
        XmlJavaTypeAdapter ad = object.getAnnotation(XmlJavaTypeAdapter.class);
        if (ad == null) 
          throw new ClassCastException("Inavlid XmlElement annotation, " + objectType
            + " is not assignable from " + el.type());
    }
    return el.type();
  } else
    return null;
}

Once that works, then we find that the XmlTypeAdapterFactory.create() method uses the wrong parameter in the match() call...rather than compare the propertyType to the originalType, it should compare it to the adaptedType instead:

if (!match(propertyType, adaptedType, false))

Of course, the JaxbAnnotationsSupportTest breaks, but I suspect this might be due to the XmlJavaTypeAdapterBean's public int v only having an XmlJavaTypeAdapter annotation and no XmlElement annotation (both would be generated by JAX-B).

Create default converter for linked lists and other common collections

It is mainly extending CollectionConverter and handling the type in the factory:

@HandleClassMetadata
public static class LinkedListConverter extends CollectionConverter {

    public LinkedListConverter(Class<E> eClass, Converter<E> elementConverter) {
        super(eClass, elementConverter);
    }

    @Override
    protected Collection<E> create() {
        return new LinkedList<E>();
    }
}

Make class metadata key configurable

Make class metadata key configurable via GensonBuilder. So instead @Class something else could be used. This would allow better interop. with other libs that have written the json.

ArrayList getter must be public after upgrade to netbeans 8.0.1

Hi. After upgrade from netbeans 8.0 to netbeans 8.0.1, my simple webservice program started to return an empty ArrayList whenever an ArrayList is returned.

In your Getting Started page, on the Object databinding section, you state, and quote "Genson provides full support for object databinding by following standard JavaBean conventions. The basic rules for databinding are: All public or package visibility fields, getters and setters will be used, including the inherited ones."

My sample program is here: https://www.dropbox.com/sh/n4u97199oojbp9x/AACwcymvjY1cl2i_rtriGCAaa?dl=0

If you go to the Persons class, and remove the public modifier from the getter, the returned Json string in only "{}".

Could you please, provide some enlightenment on this matter ?

Thanks,
Rui

float Serialization

Hello,

I use the version 1.1 of Genson and Java 7u71.
Genson fail to serialize float, I tried to debug the library, I've found that Genson use the NullConverter to convert float type. The NullConverter is created by the method create of the class CircularClassReferenceConverterFactory with the type float passed. After that, I'm lost.

The returned json is like that : "aFloat":{}.
If I switch from a float to a double it's work fine.

Genson annotations not overriding Jaxb annotations

I have a Jersey no-xml webapp that includes the GensonJsonConverter automatically. My generated, annotated JAXB pojos receive @JsonIgnore annotations on certain fields (I did not add the annotations to the accessors or mutators), but the ignore is ignored. For example, I have a createdBy field annotated thusly:
@xmlelement(name = "CreatedBy", required = true)
@JsonIgnore
protected String createdBy;

Does this ring any bells? I've attempted to make my own Genson ContextResolver and control the GensonBuilder, but it did not suffice (it's more than possible that I didn't correctly configure the builder). Looking through the JAXBBundle code, it isn't readily apparent to me how it falls back to the @JsonIgnore annotations.

Optionally Only add class metadata for non-concrete types in Genson

See question on SO.

This could be achieved by:

  • Check in serialize method of ClassMetadataConverter if the tClass.equals(obj.getClass) && serStaticTypesClassMetadata then don't ser class info.
  • Modify GensonBuilder to expose serStaticTypesClassMetadata option and use it in ClassMetadataConverterFactory.

Use sbt for genson-scala

Try to use sbt for genson-scala and maven for the java code.
The goal is to publish genson-scala for scala 2.10 and +
Abstract the different steps through a script that makes the release (mvn, sbt, doc).

Things to check: maven and sbt should both use and increment the same version.

Handle Inner class gracefully in ASMCreatorParameterNameResolver

When using ASMCreatorParameterNameResolver with a inner class, it fails with an NPE

java.lang.NullPointerException
at com.owlike.genson.reflect.ASMCreatorParameterNameResolver.read(ASMCreatorParameterNameResolver.java:61)
at com.owlike.genson.reflect.ASMCreatorParameterNameResolver.resolve(ASMCreatorParameterNameResolver.java:83)

GensonJsonConverter throws NPE if response has no annotations

Using Resteasy, I noticed that in some situations the GensonJsonConverter throws an NPE. The issue seems to stem from the private method 'find' which is used by the 'createContext' method to see if the WithBeanView annotation is present. This method does not first check to see if the annotation array is null.

Usually this does not cause an issue as Resteasy copies the annotation from the resource method to the response prior to passing it to the MessageBodyWriter which at least includes the Http Method annotation (e.g @get, @post). However the issue seems to be reproducible by throwing a WebApplicationException and passing in a custom response object that does not include any entity annotations.

Improve website

  • Move Getting started to User Guide
  • Make a short getting started
  • Improve metadata for SEO
  • Make the README nicer & more useful?
  • Add copyright & license

Fail to deserialize byte fields

private byte numByte;

numByte = (byte) 6;

getter/setters omitted

JSON:
"numByte":6

Caused by: com.owlike.genson.JsonBindingException: Could not deserialize to property 'numByte' of class class model.Simple
    at com.owlike.genson.reflect.PropertyMutator.couldNotDeserialize(PropertyMutator.java:49)
    at com.owlike.genson.reflect.PropertyMutator.deserialize(PropertyMutator.java:32)
    at com.owlike.genson.reflect.BeanDescriptor.deserialize(BeanDescriptor.java:109)
    at com.owlike.genson.reflect.BeanDescriptor.deserialize(BeanDescriptor.java:92)
    at com.owlike.genson.convert.NullConverter$NullConverterWrapper.deserialize(NullConverter.java:56)
    at com.owlike.genson.convert.CircularClassReferenceConverterFactory$CircularConverter.deserialize(CircularClassReferenceConverterFactory.java:30)
    at com.owlike.genson.convert.DefaultConverters$ArrayConverter.deserialize(DefaultConverters.java:264)
    at com.owlike.genson.convert.NullConverter$NullConverterWrapper.deserialize(NullConverter.java:56)
    at com.owlike.genson.reflect.PropertyMutator.deserialize(PropertyMutator.java:30)
    ... 27 more
Caused by: com.owlike.genson.stream.JsonStreamException: Expected a String to convert to byte array found INTEGER
    at com.owlike.genson.stream.JsonReader.valueAsByteArray(JsonReader.java:298)
    at com.owlike.genson.convert.DefaultConverters$ByteConverter.deserialize(DefaultConverters.java:570)
    at com.owlike.genson.convert.DefaultConverters$ByteConverter.deserialize(DefaultConverters.java:557)
    at com.owlike.genson.convert.NullConverter$NullConverterWrapper.deserialize(NullConverter.java:56)
    at com.owlike.genson.reflect.PropertyMutator.deserialize(PropertyMutator.java:30)
    ... 34 more

Improve DateConverter to use timestamp and dateformats

Actually people have to indicate if they want to ser/de dates as long timestamp or a string with a date format. Even if it can be configured per field via annotations, the incomming JSON might use both.

DateConverter could be enhanced to

  • serialize based on the JsonDateFormat annotation or global config (use only timestamp or string format)
  • deserialize based on the incoming value type

This has been asked on SO.

Provide conversion mechanism between types

The general requirement could be, convert object of type A to an object of type B.
In practice this would allow to convert from some DOM structure to a Pojo & vice versa. This can be quite handy when dealing with external APIs and want to map it to a DOM structure, transform it and then map it to your final type.

This would also be useful in order to implement more sophisticated deser based on json content without depending on the metadata order, see #25

Accessors/Mutators should be merged

While selecting the accessors and mutators to use, those that have the same name should be merged:

  • For example if a public field named "password" is annotated with @MyAnnotation and the corresponding getPassword is selected, then we should transpose the @MyAnnotation to the getter.

Fail fast on missing properties

At the moment we provide the ability to fail fast when the input json contains a property that doesn't map to any property in the target class, it would be nice to have the inverse. Throw an exception when an expected property is missing in the input json.
At a minimum there should be a global option to enable this for all mappings and as a bonus enable it via an annotation per property.

Propose a deep ser/de mode

In some cases we want to ser/de complex objects that are not pojo like (rpc purposes, saving complex structures to disk and reload them latter, etc), in this case it would be nice to provide an option in the builder that would:

  • use only fields with any visibility (but still exclude transient etc)
  • if a no arg ctr is not available then generate one

Extend JAX-RS en/disabling support to RestEasy

Hi,

I'm aware of a similar issue (#39) that implements disabling JAX-RS for Jersey implementation.

I think that the appeal for genson addition to an existing app is the smoother control on serialization, specially in case of migration from JAXB format to a cleaner alternative. We are facing this problem with jettison JAXB implementation that seems to be quite restrictive.

Said that, I figured out that this feature (#39) is constrained to Jersey application. Would it be possible to do such JAX-RS switching mechanism to ReastEasy implementation?

I tried to hack from the source but just achieved success by removing the META-INF/service folder declared hooks from the final JAR.

Do you know an alternative to switch genson on/of in Resteasy? If you have an idea, an you agree, I could implement it and submit a patch.

Thank you!

Add deser to instance methods to Genson class

Actually people can deserialize to an existing object, and just update it with the data from the json stream. However there is some boilerplate code to write to achieve it and it works only with Java Beans.

The idea would be to introduce some methods in Genson class, doing all that stuff and exposing a simple to use method.

Add write(name, value) methods to ObjectWriter

The idea is not to try to improve performance, but just to reduce the amount of code when using the streaming api to write object properties.

Instead of doing:

writer.writeName("key").writeValue("value")

people could do:

writer.write("key", "value")

When skiping values avoid storing strings

In some extreme cases there might be string values that are huge (ex: a byte array being ser base64) that we want to skip. Actually skiping will avoid databinding but during the decoding process, the resulting literal value will be kept in memory. This can result in a OOM if this string value is very big.

This can be implemented relatively easy:

  • By having a boolean when reading string values that will indicate not to keep this value in memory. Downside is that this check will be performed even in cases when we want to keep the string (most cases) and degrade a bit performances.
  • A more efficient alternative but uglier to implement and would increase number of LOC, would be to have a specific branch in the code that handles skipping values.

NPE in ASMCreatorParameterNameResolver

We have a case where Genson cannot serialize a validation annotation.

When Genson gets into ASMCreatorParameterNameResolver.read(class) the getResourceAsStream call returns null (maybe because the class of 'ofClass' is an on-the-fly Proxy). The inputstream 'is' then becomes null, which makes 'new ClassReader(is)' fail. We get into the finally clause, which is this:

  try {
    is.close();
  } catch (IOException e) {
  }

This of course throws an uncaught NPE upwards through the callstack.

code to manually register Genson provider for Jersey 2.9+

As noted in a previous forum post, Jersey 2.9 eliminated the auto loading feature Genson relied on to become a default JSON serializer. What code is necessary to manually register? I found that Jackson does work out of the box, but is 200+mb more bloated for the simple project I'm starting with so I'd rather not go that route. My app is using Jetty 9 with a simple ResourceConfig(Application) class for initialization

Adding org.glassfish.jersey.ext:jersey-metainf-services as a dependency does auto-register, but causes duplicate symbols with jersey-common when using the Maven Shade plugin to create a minimal, standalone jar. The app still runs, but the warnings are ugly and I'm not sure if there are any other side effects

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.