Java Basic Knowledge Hardening 103:json Parsing Framework Summary

Source: Internet
Author: User

1, Gson

Gson is an open-source Java class Library provided by Google that translates Java objects into corresponding JSON representations, and of course Gson can convert JSON strings to Java objects equivalent to them. Gson is valid for any Java object, including those that pre-exist without source code.

Now there are some open source projects that can convert Java objects into JSON. But most projects require you to include Java annotations in your class files, which you can't do when you can't change the source code. And they also do not support Java generics. But Gson the two points as a very important design goal.

Target
  • With the Tojson () and Fromjson () methods, it is very easy to accomplish the conversion of Java objects to JSON.

  • Can convert pre-existing objects that cannot be modified to JSON.

  • Supports the use of Java generics.

  • Allows a personalized representation of an object (representation).

  • supports a variety of complex objects with deep inheritance hierarchies and extensive use of generic types.

Official website: Https://github.com/google/gson
Open Source Address: Https://github.com/google/gson

2. Jackson

Jackson is relatively efficient in the project, mainly using Jackson for JSON and Java Object conversion, Jackson Library, the Java-based open source JSON format parsing tool, the entire library (using the latest version 2.2) contains 3 jar packages:

  • The jackson-core.jar--core package (required) provides an API based on "stream mode" parsing.

  • The jackson-databind--data binding package (optional) provides APIs based on the object binding and tree model. The jackson-annotations--annotation package (optional) provides annotation functionality.

Jackson's Advantages
Compared to other libraries parsed by Java JSON, such as the Json-lib, Gson package, Jackson has the following advantages:

1. Multi-processing mode, and can work well together. Starting with basic usage, there are several ways to use and produce JSON data, although most JSON packages provide only a single way of processing, but there are three complementary JSON processing methods:

    • Incremental parsing and generation (stream mode). High-performance, low-overhead sequential access. This is the lowest-level approach, equivalent to the SAX and Stax APIs used to process XML. All packages must have such analyzers inside, but not all of them are public.

    • Tree-based Data schema (JSON DOM). A tree is a natural conceptual model that describes JSON content, so many packages provide the ability to process JSON as a logical tree. This is a flexible model that works well for a class of tasks, and prototype processing or ad hoc access is also quite remarkable.

    • Data binding (JSON and Pojo are converted to each other.) Extremely convenient, usually higher access efficiency than tree mode, is also suitable for Java developers common natural data binding way. Often used in most Java rest frameworks, such as Jax-rs.

2. Can use any construction and factory method (not just the default 0 parameter method)

    • Most data (for JSON and XML) binding tools require a defined and parameterless constructor, instantiate Java objects, and set properties by setter or directly access fields. Unfortunately, it makes it difficult to use "immutable object" mode, which is also different from the access pattern in normal code.

3. Not only annotations, but also mixed annotations!

    • While there are many benefits to using Java annotations to define metadata (such as type safety, compile-time checking, eliminating separate XML configurations, Dty principles, and so on), there are drawbacks: as is obvious, adding annotations must be able to modify the class. And you usually can't (and should not) modify the code of a third-party library, at least not just the JSON serialization configuration aspect. But what if you can only loosely correlate annotations dynamically, instead of embedding them in your code? I think it's a great idea, no matter how much you know about Jackson's hybrid annotations: You can associate a comment with a target class (declared as part of a proxy interface or class) The target class is treated as if it were the annotation declared by the target class itself.

4. Full support for generic types

    • Generics are now a complete part of Java development, however, not all JSON libraries support generics, and even errors occur when dealing with very complex data types.

    • Take the following generics as an example:

    • public class Wrapper<t> {public T value,} public class Listwrapper<e> extends Wrapper<list<e>> { }

    • To deserialize these types of data, the code is as follows:

    • listwrapper<integer> w = Objectmapper.readvalue ("[{" Value ": 13},{" value ": 7}]", New typereference< Listwrapper<integer>> () {});

    • Jackson had a little trouble figuring out what was necessary and generating the desired value, but it was the only Java package that supported generics (or more).

5. Polymorphic types

    • Here's another factoid: inheritance and polymorphic types are a great way to use for object-oriented development, but they are also the pita of any system that implements data-binding capabilities.

    • Most of the complexity of ORM (such as Hibernate) is due to the need for flattened and non-flattened data functions along the hierarchy of inheritance, as well as for data serialization packages like JAXB. It's no wonder that, at the time, only a handful of Java packages supported JSON deserialization of polymorphic types, most requiring user-created application code to explicitly type-parse.

6. Materialized interface (even less monkey code to write!)

    • While supporting polymorphic types is a powerful feature-there is plenty of inherent complexity-here's how to simplify things: materialized interfaces (or abstract classes).

    • The given interface is as follows:

    • Public interface Beans {public int getX (), public void SetX (int value);}

    • You might want to skip this step "bean interface implementation, which contains twice times the code of the Class", and directly processing:

    • Bean bean = objectmapper.readvalue (JSON, bean.class);

    • This magical function (also known as "Mr. Bean") can be achieved with a single line of configuration.

7. Support Parent/child references (one-to-many, ORM)

    • Through the previous universal feature set, we summarized something more specific: the ability to cleanly handle certain subsets of the loop type as a parent/child link. These are closely coupled references, where two objects are cross-referenced in a hierarchical way, such as the Association of Parent/child tree nodes, or, more commonly, the description of the Inter-table join (join) used by ORM.

    • For reference issues (or, more generally, circular references), JSON does not have a natural way of handling them. , unlike Java objects, no identity information is available. A common workaround is to mark only one ignored reference (Jackson can do this by using the @ jsonignore annotation), but the disadvantage is that the actual coupling target is lost when deserializing. Jackson has a simple annotation-based solution to the problem: two references require an annotation (a @jsonmanagedreference annotation for a "child" connection, a @JsonBackReference annotation for a "parent" or "return" connection), and on this basis, Jackson knows to omit the serialization of the reverse reference, but to restore it when deserializing the object. This approach is suitable for typical ORM use cases.

    • Important API

    • Core package: Jsonpaser (JSON stream read), Jsongenerator (JSON stream output).

    • Data binding Package: Objectmapper (build tree mode and object binding mode), Jsonnode (tree node).

Official website: http://wiki.fasterxml.com/JacksonHome
Open Source Address: Https://github.com/FasterXML/jackson

3, Genson

Genson is a complete library of Java and JSON transformations, providing comprehensive data binding, streaming operations, and more. Published based on the Apache 2.0 protocol.

Characteristics

  • Easy-to-use, fast, highly configurable, lightweight small jar package.

  • Supports comprehensive data binding and efficient read and write of streams.

  • Supports polymorphic types (capable of serializing an unknown type).

  • There is no need for the default parameterless constructor method and the pass parameter is not only NULL, but encourages invariance. It can be replaced by a factory method instead of a constructor function.

  • Full support for Java generics.

  • Easy to filter and extend file attributes, no need to comment and mix.

  • Genson provides a complete implementation of the JSR353.

  • Support for annotations and types starts with Genson 0.95JAXB.

  • Automatic support for JSON implementation in JAX-RS.

  • Constructs serialization and deserialization of a map collection with complex keys.

Goal

  • Allows users to implement new functionality with as many extensions as possible by using a neat, simple way.

  • Provides an easy-to-use API.

  • Try to be fast, scalable, or even more than the highest performance library.

  • Generics are fully supported.

  • Support for classes without source code.

  • Provides an efficient streaming API.

Pojo Data Binding
The main entry point for the Genson library is the Genson class, which provides serialization from a Java object to a JSON object and from a JSON stream to a Java object. Genson instances are immutable, thread-safe, and reusable. In general, the recommended approach is to have a separate instance for each configuration type.
The usual way to use it is to use Genson to read JSON and some Pojo matches. Conversely, you can read Pojo to write JSON.

Java Collection
You can also use standard Java collections like map and list. If you do not tell Genson the type you are using, Genson deserializes the JSON array into a List,json object in Java and deserializes it into a map with a long or double attribute in the object.

Deserialization common Type
Can be deserialized into a generic type, such as an Pojo array.

Custom Genson
If the default configuration provided by Genson does not meet your needs, you can customize it by Gensonbuilder. For example, it is possible to implement output indentation, serialize all objects with their runtime type, and deserialize a class that does not provide a default parameterless construction method that can be implemented using the following configuration.

Official website: http://wiki.fasterxml.com/JacksonHome
Open Source Address: Https://github.com/FasterXML/jackson

Java Basic Knowledge Hardening 103:json Parsing Framework Summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.