700 Software
700 Software

Reputation: 87833

Smallest (less internal code), up-to-spec JSON parser in Java

I have seen there are many JSON parsers in Java. Some target speed, some target accuracy, some target flexibility (streaming, buffering, etc). Some have use special subclasses of the collections api instead of using the ones that are already there. That seems bloated to me.

So I would like to know, which one(s) tackle the job of string to object conversion in the shortest/simplest manner? (as in, less code)

Edit: I am sorry I was not clear. What I mean is the smallest parser. So if one parser was 600 lines and the other was 400 lines. I don't care which is faster so much as which is easier to understand. This is not to be confused with how many lines it takes to invoke the parser. I expect almost all would be just a few lines of code and if I have to add a convenience method that is OK.

Purpose is more of an educational thing, how is it done, and the wish to use APIs where it is easy to see how it works.

Upvotes: 3

Views: 2331

Answers (6)

Rapsack
Rapsack

Reputation: 39

Let me mention the solution at https://github.com/KasparNagu/plain-java-json using 107 lines for the parser class.

Yet of course, if you plan to use it, you're way better off with one of the proven implementations mentioned above.

Upvotes: 2

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64066

My parser is a single class, and 740 lines after stripping comments; it's efficient, fully functional and has a number of options for parsing "human readable" JSON.

Upvotes: 1

ralfstx
ralfstx

Reputation: 4033

If you're looking for a really minimal JSON parser, you should have a look at these:

Both are complete JSON implementations that consist of only a dozen Java classes.

Upvotes: 1

Chris Dennett
Chris Dennett

Reputation: 22731

What about http://code.google.com/p/json-smart/? It's very small, apparently. Seems to be up to date.

Upvotes: 3

ColinD
ColinD

Reputation: 110094

Google Gson is my preference for this. All you have to do is make a class with a structure that matches a JSON object and converting JSON can be as simple as:

Foo foo = new Gson().fromJson(json, Foo.class);

If there's something more complex you need to do, you only need to add some field annotations or write a custom serializer/deserializer (which is pretty easy) and register it once. Actually converting JSON to objects is always just a matter of calling gson.fromJson(...).

Upvotes: 1

Amir Raminfar
Amir Raminfar

Reputation: 34179

I can think of two. Jackson or Gson. I'll add some examples.

GSON

Gson gson = new Gson();
Long one = gson.fromJson("1", Long.class);

Jackson

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);

Jackson is a little faster so its up to you what you want.

Upvotes: 3

Related Questions