Wiki

Clone wiki

jsonij / Home

JSON in Java (JSONiJ) Wiki

Welcome to the main guide for the new version of JSONiJ. JSONiJ is a JSON Parser, JPath Implementation and Marshaller implemented in Java. Its easy to use and it has good performance.

My documents for JSONiJ have come and gone with the various accounts that I have created around the place so I figure that the safest bet is to store this content with the source itself.

Quickstart

Start here if you have a simple JSON job to do.

Install JSONiJ (Maven)

<dependency>
    <groupId>cc.plural</groupId>
    <artifactId>jsonij</artifactId>
    <version>0.3.1</version>
</dependency>

Install JSONiJ (jar)

Download a release or a snapshot of JSONiJ and add it to your classpath.

Parse JSON String

Parsing a String of JSON is pretty straight forward;

JSON resultJSON = JSON.parse("{\"key\":[1,2.3,0.4,-5,-5.92,0.001E1,-0.045E45,987654321]}");

You can then traverse resultJSON similar to an XML DOM.

Parse JSON File

JSONiJ parses any JSON source wrapped in a java.io.InputStream and, once again, reading it in is pretty straight forward;

URL file = ClassLoader.class.getResource("/config.json");
JSON resultJSON = JSON.parse(file.openStream());

Pull Values From Parsed JSON

The most basic method to pull values out is using the Value API like the following;

Value jsonArray = resultJSON.get("key");

If you feel a little more adventurous then you can use JPath;

Value jsonArray = JPath.evaluate(resultJSON, "/key");

If you are on the run with JPath then why not just grab what you want, like the 3rd element of the key array;

Value jsonArray = JPath.evaluate(resultJSON, "/key[2]");

Sweet.

Quickly Persist Java Classes to JSON

The JSONMarshaller will allow you to very quickly dump Java classes to JSON. For example the BasicTestObject can be dumped without fuss;

BasicTestObject test = new BasicTestObject();
test.setId(321);
test.value = "I am a String";
test.getClassMapping().put("Java Date Class", Date.class);
test.getClassMapping().put("JSON Marshaller", JSONMarshaler.class);
System.out.println(JSONMarshaler.marshalObject(test).toJSON());

This results in;

{"id":321,"classMapping":{"JSON Marshaller":"cc.plural.jsonij.marshal.JSONMarshaller","Java Date Class":"java.util.Date"},"value":"I am a String"}

Done.

Releases

I always use low version numbers. Don't be put off by the fact that the version is not 1.X.Y+

Version 0.3.1

Few small changes including;

  • Fix for Regex JPath Predicate.
  • Few performance fixes.
  • Javadoc updates to allow Java 8 to create docs.

Older version notes can be found here.

Contact

I am happy to help out with any questions wherever I can. Simply contact me through BitBucket or raise an issue.

Updated