share
Stack OverflowA better Java JSON library?
[+669] [16] sanity
[2008-12-03 20:32:20]
[ java json ]
[ http://stackoverflow.com/questions/338586/a-better-java-json-library ] [DELETED]

Can anyone recommend a good Java JSON library (better than the one from http://json.org/)? I've also found JSON-lib, which definitely looks like an improvement, but I'm wondering if there is anything that is even better than that?

I have added a hyperlink to my parser in my answer (softwaremonkey.org/Code/JsonParser). - Lawrence Dol
(32) One thing that'd help is to explain in which ways you want alternative to be better -- more functionality, more convenient, more efficient, better documentation or something else? - StaxMan
(3) Yes... what is wrong with the existing ones? Only thing I can think of is type-safety, but when I tried to fix that, it turned out to be impossible. - Thomas
(49) A lot has changed since this question was asked 2 years ago. Here is a more recent benchmark of java serializers: code.google.com/p/thrift-protobuf-compare/wiki/Benchmarking Notable: "Omitted from the first three charts: json/google-gson and scala. These serializers are so slow, they would break the scale of our charts. See below for the naked data." I'm using Jackson Json on an android app, which is incredibly fast, and come a very long way since this question was asked/answered. - FrederickCook
(4) One of the shortcomings of the json.org library is that it accepts unquoted strings, breaking the JSON specification. At the very least, they could have included a parameter to enable strict parsing. - user359996
(1) Frederick, I think your link should be in an answer, or at least mentioned in bigger text in the question. - Shurane
(7) "closed as not constructive by Kev". Seeing all the information and activity, it does look very constructive and perhaps it shouldn't have been closed so eagerly! - RedGlyph
Open questions that shouldn't be open obviously cause so much more harm than closed questions that shouldn't be closed, so let's be thankful that people err on the side of closing questions.</sarcasm> - sanity
A lot has changed since this question was asked 5 years ago. Oracle has produced a standard JSON API (JSR 353) for Java EE 6 which is available in Maven, and the reference implementation used in Glassfish is also available in Maven. - Thorbjørn Ravn Andersen
@ThorbjørnRavnAndersen - consider editing top answer for Java JSON library with your comment. - Alexei Levenkov
json-io (github.com/jdereg/json-io). Handles cyclic Java object graphs, reads JSON into Java objects or Maps, can serialize / clone Java graphs, pretty prints JSON. - John DeRegnaucourt
[+377] [2009-04-24 09:03:31] sroebuck [ACCEPTED]

I notice that there is also a library called google-gson [1]. I haven't tried it yet. Here's how it describes itself:

Gson is a Java library that can be used to convert Java Objects into its JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.

Check out if your version of Java already contains JSON API - see Java API for JSON Processing, July 2013. [2] and JSR 353 [3].

[1] http://code.google.com/p/google-gson/
[2] http://www.oracle.com/technetwork/articles/java/json-1973242.html
[3] https://jcp.org/en/jsr/detail?id=353

(44) +1. Gson is great. Here's an use example: stackoverflow.com/questions/1688099/converting-json-to-java/… - BalusC
(13) This is the solution I went with in the end, and months later I'm very happy with my decision. - sanity
(4) The problem with Gson (at least in versions up to 1.4) is that it is not able to handle circular references. This is very common in some scenarios (JPA/JDO objects being serialized to JSON...) - Guido García
(4) Most java json libs do not deal with cyclic deps -- that's more domain of object serialization frameworks. FWIW, XStream with Badgerfish (jettison) does handle them (since it's full object-serialization framework, although resulting json looks ugly, as its xml based, just converts to json via badgerfish) - StaxMan
GSon uses the same design protocol JSON.org went with when developing JSONObject and JSONArray. - Buhake Sindi
(2) Design protocol meaning... ? Similar API, or something? I don't see much similarities between the two (which I think is good thing for GSON) - StaxMan
Gson is great, and has high quality documentation too. Check out the User Guide to get started. - Jonik
GSON is awesome, brings a python like feel to Java, well, atleast for JSON purposes - v1v3kn
When I wanted to use JSONLib; I found out that the jar file that is available in json-lib.sourceforge.net has some class dependencies and it needs to be used by some other jar files, that contain that classes. So I used Gson - sajad
Incredibly, GSON types don't implement Serializable nor Cloneable.... Really too bad - Lukas Eder
GSON is a good library, we have been using it in our project from past 2years, and it works fine. - Sangram Anand
(2) Gson is very slow. I've a situation with a client that makes use of gson that converts, 300 objects at a time, from json to objects with gson and there are about 9-50k objects to convert. This takes 10-60 minutes on a mobilephone/hand held computer. - Johan
@Johan What would be more reasonable performance and what other libraries deliver? - eflat
@eflat it seems to depend on object size and how you handle the mobile phone memory etc, not only gson/jackson etc. However, Jackson performed better for us. - Johan
json-io (github.com/jdereg/json-io) handles cyclic graphs, in addition to reading / writing any Java graph (marked as Serializable or not). - John DeRegnaucourt
1
[+312] [2009-11-10 18:42:47] Piko

I've used JSONLib [1], FlexJSON [2] and Gson [3] all with great success. Each has its best use.

  • JSONLib is awesome as a core JSON library when you just want to process all elements of a JSON.

    JSONArray cms = jsonObject.getJSONArray("containerManifests");
    for (Object o : cms) {
        JSONObject cm = (JSONObject) o;
        String cmId = cm.getString( "cmId" );
    }
    
  • FlexJSON shines with its deepSerialize method that can properly handle serializing all get methods presented in a bean obtained from Hibernate (lazy loaded).

    ContainerManifest cm = cmDAO.read( cmId );
    String cmJson = new JSONSerializer().deepSerialize( cm );
    
  • Gson seems to be the best API to use when you want to convert a json to a Java class. Other API only call set methods on the high level classes in the bean structure. If you have a deep bean structure, everything else will be implemented with dyna beans. Causes havoc elsewhere. Gson fully populates all low level values by calling all set methods for all data found in the JSON.

    Gson gson = new Gson();
    ContainerManifest cm = gson.fromJson( json, ContainerManifest.class );
    

YMMV [4]

[1] http://json-lib.sourceforge.net/
[2] http://flexjson.sourceforge.net/
[3] http://code.google.com/p/google-gson/
[4] http://en.wiktionary.org/wiki/your_mileage_may_vary

(4) "Gson fully populates all low level values by calling all set methods for all data found in the JSON." Actually, Gson does not use set methods when deserializing (nor does it use get methods when serializing). Instead, Gson uses reflection to directly reference the fields. Some future version of Gson will reportedly support using getters/setters instead of fields. A comment on issue 232 includes the possible changes necessary to enable getter support. - Programmer Bruce
When I wanted to use JSONLib; I found out that the jar file that is available in json-lib.sourceforge.net has some class dependencies and it needs to be used by some other jar files, that contain that classes. So I used Gson - sajad
2
[+206] [2008-12-03 20:38:54] Matt Solnit

I can't truly recommend this, because I've never used it, but Jackson [1] sounds promising. The main reason I mention it is that the author, Tatu Saloranta, has done some really great stuff (including Woodstox [2], the StAX implementation that I use).

UPDATE: A year ago I started actually using Jackson and I can confirm that it is awesome :-). I especially like being able to switch back and forth between using a "tree model" (similar to XML DOM) and object mapping. For example, let's say I have the following JSON:

{
  "parent":
  {
    "irrelevantobject":
    {
      "foo": 1,
      "bar": 2
    },
    "interestingobject":
    {
      "qux": 3
    }
  }
}

The data I really want is inside "interestingobject". The rest is fluff that I don't care about (maybe returned by some REST API).

In addition, I have the following Java class:

public class InterestingObject {
  int qux;
}

I can use the following code to navigate through the JSON document and then map the object I want:

// Create a standard Jackson mapper object.
ObjectMapper mapper = ...

// Find the node I want using a DOM-like model.
JsonNode rootNode = mapper.read(theJsonString, JsonNode.class);
JsonNode interestingObjectNode = rootNode.get("parent").get("interestingobject");

// Parse it into a Java object.
MyInterestingObject interestingObject = mapper.treeToValue(interestingObjectNode,
  MyInterestingObject.class);

Without this capability, I would be stuck writing extra wrapper classes.

Another impressive Jackson feature is the ability to map classes that you don't own (in other words, map a third-party Java class when you can't change the source code). See this blog entry [3] for more details.

Jackson is amazingly customizable. I could list many, many more features :-).

Finally, don't miss 7 Killer Features that set Jackson apart from competition [4].

[1] http://jackson.codehaus.org/
[2] http://woodstox.codehaus.org/
[3] http://www.cowtowncoder.com/blog/archives/2009/08/entry_305.html
[4] http://www.cowtowncoder.com/blog/archives/2010/11/entry_434.html

(14) I second that, Jackson is a wonderful piece of work- much more efficient. - Robert Munteanu
(1) Just curious - why the downvote? Does someone have different (i.e. negative) feedback about Jackson? - Matt Solnit
I tried Jackson when I was doing interoperability between .NET and Java and dates was a mess for me. I don't understand why it's done the way it's done in Jackson. The idea behind JSON is that I should just be able to shuffle data around, I don't have to care about date formats, timezones and all that crap. When I was sending data back and forth between js and c# I had zero problems whatsoever. - Anders Rune Jensen
(9) Hi Anders! JSON does not have a Date type (just strings, numbers, booleans), and each lib therefore has to define its own convention. That can lead to interoperability problems, esp. since default serializations for different languages are different. - StaxMan
(8) One thing that might be interesting wrt Jackson is the performance aspect (Jackson is specifically designed as a very high performance JSON package), see [code.google.com/p/thrift-protobuf-compare/wiki/Benchmarking] and [cowtowncoder.com/blog/archives/2009/09/entry_326.html] - StaxMan
I've just ran into some problems with Jackson, Hibernate and Spring, however, I don't know if this issue is related to Jackson or Spring or Hibernate ... see stackoverflow.com/questions/3325387/… - Ta Sas
user268098: I think most Java JSON handling libraries have issues with cyclic dependencies, and most have some ways to either exclude just references, or handle them with annotations (I added an answer in the other question to point out one way to do that with Jackson). Of alternatives I think only XStream+Jettison handles cyclic dependencies automatically, if enabled. - StaxMan
(2) I second this. Jackson is also easy to use. See: spring-java-ee.blogspot.com/2010/12/… - Hendy Irawan
(1) I have used Jackson a lot, and it blows the competition away. - brianm
(2) FYI, it appears that Jackson has moved to a new home within codehaus.org. Can you update your original link? To wit: jackson.codehaus.org - Piko
(1) I second Jackson in favour of FlexJson; FlexJson lacks a default Jax-RS provider and doesn't correctly parse generics (like SomeObject<T extends MyClass>). Also Jackson has very elegant configuration (once you find out how to plug it in!) and mixins allow great flexibility! - Riccardo Cossu
@StaxMan Was that the nice way of saying ms handles dates poorly? "No, this custom /Date string is WAAAAY better!" lulz - Gracchus
I third this. Jackson is ahead of the pack in so many ways. granted GSON is simpler for a newbie. But the return on the initial time-investment is huge. And the performance is actually comparable to some of the highly fine-tuned serialization schemes(protobuf, thrift, etc) - pellucide
3
[+23] [2010-02-26 21:59:28] Aleksandar Totic

Just went through this exercise. I wanted to represent arbitrary JSON as nearest Java equivalent. For me that is a HashMap/ArrayList Object. json-simple [1] was excellent: tiny, with a simple API that generates HashMap/ArrayList with a single call. It also has extensions for object serialization/deserialization.

I also tried gson: API was very object serialization oriented, and type safe, could not do what I needed simply.

[1] http://code.google.com/p/json-simple/

(2) +1 The way it encodes/decodes to maps, lists and primitive objects appeals to my Python experience too. - aitchnyu
FWIW, almost all Java JSON libraries support this conversion mode, including GSON, Jackson and Genson. - StaxMan
4
[+18] [2008-12-03 22:11:03] kolec

I can recommend http://json-lib.sourceforge.net/. We have used it in few projects without problems.


(10) This bug has made me sad: sourceforge.net/tracker/… - dfrankow
(4) also, it has dependencies - njzk2
5
[+13] [2008-12-03 22:15:55] Gennady Shumakher

I have no personal experience with the following approach,but it could make sense to consider:

XStream [1](xml <-> java data binding) with Jettison [2] driver (xml<->json mapper), more details are available here [3].

That's from their site:

XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("product", Product.class);
System.out.println(xstream.toXML(product));
[1] http://xstream.codehaus.org/index.html
[2] http://jettison.codehaus.org/
[3] http://xstream.codehaus.org/json-tutorial.html

JAXB 2.0 also has support for JSON serialization using Jettison - Mark Renouf
Actually, any XML package that can use Stax API can use Jettison -- JAXB does, so there's no extra work involved (same is mostly true for XStream too, although it may have some additional support). - StaxMan
I found XSteam useful when converting Objects back and forth between Java & XML or JSON with the Jettison driver. If you want to influence the representation in XML/JSON to a larger degree than just naming tags and ignore properties, you'll be better of using one of the other libraries mentioned above. - wwerner
(4) Isn't this a little perverse? - user359996
6
[+10] [2009-12-03 16:37:35] inder

Gson can also be used to serialize arbitrarily complex objects. Here is how you use it:

Gson gson = new Gson();
String json = gson.toJson(myObject);

Gson will automatically convert collections to JSON arrays. Gson can serialize private fields and automatically ignores transient fields.

While deserializing, Gson can automatically convert JSON arrays to collections or arrays. Gson uses the specified class as the primary specification for deserialization. So, any extra fields available in the JSON stream are ignored. This helps design secure systems that prevent injection attacks.

You can also extend Gson's default serialization and/or deserialization behavior by registering custom type adapters.

For more details: see the user guide at the project: http://code.google.com/p/google-gson/
Disclosure: I am one of the co-authors of Gson.


And yet another example is here: stackoverflow.com/questions/2496494/… - dma_k
Any plans to support circular dependencies in the near future? - Behrang
You can file a feature request for the project, if there isn't one. I know many developers would like to have this. - StaxMan
7
[+9] [2008-12-04 20:06:04] aaronroyer

I've been meaning to try Flexjson [1]. It looks like it uses reflection on bean-style properties and uses similar rules as Hibernate/JPA lazy-loading for serialization, so if you give it an object to serialize it will leave out collections (unless you tell it to include them) so you don't end up serializing the entire object graph. The json.org library does pretty well with serializing basic beans with reflection, but doesn't have these advanced features. Might be worth checking out, especially if you use an ORM solution.

[1] http://flexjson.sourceforge.net/

I like FlexJSON as well and even modified it to be compatible with Microsoft's JSON serializer really easily. - Chad Grant
8
[+7] [2008-12-03 22:39:31] carson

I've used JSON Tools library [1] and it works well.

[1] http://jsontools.berlios.de/

9
[+7] [2009-12-16 20:55:46] Nicholas Key

You may try using GSON. It's downloadable at http://google-gson.googlecode.com/files/google-gson-1.4-release.zip

Quite simple to use actually. I used it to parse JSON results from Yelp and there is a simple example here:

  URL URLsource = null;
  JsonElement jse = null;
  BufferedReader in;
  try {
   URLsource = new URL("YELP_API_REQUEST");
   in = new BufferedReader(new InputStreamReader(URLsource.openStream(), "UTF-8"));
   jse = new JsonParser().parse(in);
   in.close();
   System.out.println(jse.toString());
   JsonArray jsa = jse.getAsJsonObject().getAsJsonArray("businesses");
   System.out.println(jsa.size());

   for (int i= 0; i<jsa.size(); i++ ) {
    System.out.println(jsa.get(i));
    System.out.println("===========================================================");
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

(1) Hi, based on ur experience, is the GSON support JDK1.4 by any chance? I can't find the documentation re the JDK it supports. Thanks. - Nordin
10
[+7] [2011-04-04 13:46:22] YumYumYum

҉ works

I was looking for a very simple way to do Php json encode in (server) and Java json decode (client), all seems too much to do only to achieve this.

I came out to this which is really simple and it works perfect. Please see: more details click here [1]

[1] http://stackoverflow.com/questions/3831680/httpservletrequest-get-post-data/5539252#5539252

11
[+5] [2008-12-03 23:12:56] Lawrence Dol

I wrote a JSON "pull-api" parser (3 classes, 18K), which I really like using. I find the pull metaphor much more usable than the event metaphor, and creating a document tree using pull is trivial.

FWIW I didn't much care for the www.json.org parser either. My biggest complaint with the offerings out there is the size of them - we target a download-constrained applet market. I remember lying in bed one night at about 2am wondering "how hard could it be", after a bit I got up and started writing - this tiny parser is the result [1].

JSON Tools looks good too.


The following generalized recursive code uses my parser to parse a JSON file into a "DataStruct" - essentially a map of lists (Note that DataStruct and Callback are objects from another package which are not published with this parser:

/**
 * Parse a generalized data structure from a JSON input stream.
 * <p>
 * All values are added using the <code>crtmbrcbk</code> callback.
 * <p>
 * <b><u>Reminder</b></u>
 * <p>
 * When using a reflected method, don't forget to configure your code obfuscator to retain it in unobfuscated form.
 *
 * @param psr       The parser to use.
 * @param tgt       Target object to which to add members; if this is null a new object is created using the callback.
 * @param maxlvl    Maximum level to recursively parse substructures, including arrays (objects at a deeper level are silently ignored).
 * @param crtmbrcbk A callback object invoked to create a member value.
 * @see             #createMemberCallback(Object,String)
 */
static public Object parseObject(JsonParser psr, Object tgt, int maxlvl, Callback crtmbrcbk) {
    return _parseObject(psr,tgt,maxlvl,crtmbrcbk,new Object[4],false);
    }

static private Object _parseObject(JsonParser psr, Object tgt, int maxlvl, Callback crtmbrcbk, Object[] crtprm, boolean arr) {
    int                                 evt;                                    // event code

    if(tgt==null) { tgt=crtmbrcbk.invoke(crtprm,psr,null,"",null); }

    while((evt=psr.next())!=JsonParser.EVT_INPUT_ENDED && evt!=JsonParser.EVT_OBJECT_ENDED && evt!=JsonParser.EVT_ARRAY_ENDED) {
        String  nam=psr.getMemberName();

        switch(evt) {
            case JsonParser.EVT_OBJECT_BEGIN : {
                if(nam.length()>0) {
                    if(maxlvl>1) { _parseObject(psr,crtmbrcbk.invoke(crtprm,psr,tgt,nam,null),(maxlvl-1),crtmbrcbk,crtprm,false); }
                    else         { psr.skipObject();                                                                              }
                    }
                else {
                    _parseObject(psr,tgt,maxlvl,crtmbrcbk,crtprm,false);
                    }
                } break;

            case JsonParser.EVT_ARRAY_BEGIN : {
                if(!arr) {
                    _parseObject(psr,tgt,maxlvl,crtmbrcbk,crtprm,true);            // first level of any array is added directly to the inherently list-supporting object
                    }
                else {
                    if(maxlvl>1) { _parseObject(psr,crtmbrcbk.invoke(crtprm,psr,tgt,nam,null),(maxlvl-1),crtmbrcbk,crtprm,true); }
                    else         { psr.skipArray();                                                                              }
                    }
                } break;

            case JsonParser.EVT_OBJECT_MEMBER : {
                crtmbrcbk.invoke(crtprm,psr,tgt,nam,psr.getMemberValue());
                } break;
            }
        }
    return tgt;
    }
[1] http://www.softwaremonkey.org/Code/JsonParser

crtmbrcbk.invoke(crtprm,psr,tgt,nam,psr.getMemberValue()); What are you, Polish? :) Joking, of course. - Esko
12
[+5] [2011-05-30 02:39:53] user392412

I recommend fastjson [1] (for .NET); just as its name suggests, it's really fast.

[1] http://fastjson.codeplex.com/

Aren't we talking about Java libs? - gustavohenke
13
[+3] [2010-03-27 22:55:35] Sam

I liked J2J - Json2Java [1] from Sourceforge.

Really easy to map JSON to almost any java object by only annotating the class using JsonElement and then passing the java and class to JsonReader like:

MyClass myclass = (MyClass) new JsonReader(MyClass.class, jsonString).toObject();
[1] http://sourceforge.net/projects/json2java/

14
[+2] [2011-03-01 08:22:51] joshis

I will add one more tip for excelent JSON<->JAVA binding lib PoJSON, it is written specifically for the NetBeans IDE [1] (by Petr Hrebejk) and thus it is used in production on large project.

It is easy to use in any project, it is just not placed on the web as a separate project (afaik), however it is in a separate package "org.codeviation" here:

http://hg.netbeans.org/main/file/9609b899e64d/kenai/src/org/codeviation

[1] http://netbeans.org

15
[+2] [2011-06-14 16:09:58] user252690

After exploring and actually using most of the major libraries listed here, I ended up writing a simplified API that is much easier to use and more fun to work with:

http://sharegov.blogspot.com/2011/06/json-library.html


16