A 250 lines single-source-file hackable JSON deserializer for the JVM. Reinventing the JSON wheel.

Related tags

JSON jsonwheel
Overview

JSON Wheel

Have you ever written scripts in Java 11+ and needed to operate on some JSON string? Have you ever needed to extract just that one deeply-nested value of an application/json response without modelling the whole hierarchy? Have you ever felt someone should indeed reinvent that wheel and provide the JVM universe with yet another JSON deserializer?

If the answer to any of those is "yes" then look no further, JSON Wheel's got you covered. It's a 250 lines single-source-file hackable JSON deserializer written in plain Java.

If the answer is "no": Fine by me, I still had fun writing it the thing. :-)

It is ...

  • small
  • deserialization-only
  • hackable
  • compatible to JDK 8+
  • dependency-less
  • not tooo slow

It is not ...

  • trying to be 100% spec-conforming
  • typed (except for its own API's types)
  • safe for malformed input
  • safe for malicious input (at least I don't give that guarantee)

Usage

Within Your Script

  1. Copy the content of the most recent version of JsonWheel.java as-is into your existing script.
  2. Remove imports if colliding with your pre-existing ones.

Within Your Project

  1. Copy the most recent version of JsonWheel.java as a file into your project's source directory, e.g. /src/main/java.
  2. Adjust the package declaration, i.e. introduce one, if needed.

With JBang's //SOURCES

  1. Create a JBang script, e.g. with jbang init.
  2. Add the //SOURCES JBang directive, as demonstrated here. If you care for your script to not break, you best set a version directly in the link and don't use the main blob.

Then you can ...

1) Deserialize JSON objects

var json = """
    {
        "foo": 1,
        "bar": "baz",
        "qux": null
    }""";

var node = JsonWheel.read(json);
var foo = node.get("foo").val(Integer.class); // 1
var bar = node.get("bar").val(String.class);  // "baz"
var qux = node.get("qux").val(String.class);  // null

2) Deserialize JSON arrays

e.val(Integer.class)) .toList(); // 1 2 3">
var json = """
    [
        1,
        2,
        3
    ]""";

var node = JsonWheel.read(json);
var list = node.elements()
        .stream()
        .map(e -> e.val(Integer.class))
        .toList();  // 1 2 3

3) Deserialize "complex" JSON

e.val(Integer.class)) .toList(); // 1 2 3 var baz = node.get("foo").get("baz").val(String.class); // "qux"">
var json = """
    {
        "foo": {
            "bar" : [
                1,
                2,
                3
            ],
            "baz": "qux"
        }
    }""";

var node = JsonWheel.read(json);
var bar = node.get("foo").get("bar").elements()
        .stream()
        .map(e -> e.val(Integer.class))
        .toList(); //   1 2 3
var baz = node.get("foo").get("baz").val(String.class); //  "qux"
Comments
  • Boolean values

    Boolean values

    Hi, thank you for this library.

    I noticed a problem handling fields when a literal value starting with n, f or t is supplied.

    The error is shown in this test which is passing when ran against the current code.

    This PR offers a fix and some test for it.

    Cheers, Enrico

    opened by enr 4
  • Support escapes and proper numbers

    Support escapes and proper numbers

    The current parser doesn't properly support all valid escapes and also doesn't support all valid floating point numbers:

    • officially only ", /, \ and the letters b, f, n, r, t, u are allowed for escapes. But perhaps you don't mind being more flexible than the standard, but
    • the parser needs to support \uxxxx to be able to accept all valid JSON documents, and
    • numbers without a . can also be valid numbers, eg. 5e10 is a valid number (and would have to be parsed as a Double).

    It's probably a good idea to take a look at syntax diagram here: https://www.json.org/json-en.html

    There is also a test suite that's very useful: https://www.json.org/JSON_checker (at the bottom where it says "test suite")

    enhancement 
    opened by quintesse 3
  • Improve testsuite

    Improve testsuite

    • [x] Add json.org's testsuite (https://www.json.org/JSON_checker/test.zip). At least add the pass ones. Let's see about the fail ones.
    • [x] Reorganize existing tests. Make sure JSON Wheel always outputs the same as Jackson.
    • [x] Cover failure paths.
    • [x] Add integerUnderflowLargeNegativeToDoublePrecision
    enhancement 
    opened by romanboehm 2
  • Various improvements

    Various improvements

    N.B.: If the individual items get to big I might split them off into separate issues. This is more of a collection of thoughts for now.

    • [x] Incorporate a ./mvnw test invocation into [prepare-]release.sh.
    • [x] Integrate the two "large" switch statements into a single one.
    • [x] Add a check for uncommitted items to release.sh.
    enhancement 
    opened by romanboehm 0
  • Make source compliant with Java 8

    Make source compliant with Java 8

    At the moment, there's no reason not to. The source is already compliant and more folks could use JsonWheel, e.g. with JBang. The only reason to keep the 11 baseline would be not wanting to maintain it forever on Java < 11.

    enhancement 
    opened by romanboehm 0
  • Make number parsing more spec conforming

    Make number parsing more spec conforming

    • [x] Don't allow all letters
    • [x] Provide custom exception instead of NumberFormatException
    • [x] Handle large numbers automatically
    • [x] Handle e-notation better
    bug enhancement 
    opened by romanboehm 0
Owner
Roman Böhm
Father, husband, AC/DC listener, software developer at Spreadgroup. Some of it professionally.
Roman Böhm
MapNeat is a JVM library written in Kotlin that provides an easy to use DSL (Domain Specific Language) for transforming JSON to JSON, XML to JSON, POJO to JSON in a declarative way.

MapNeat is a JVM library written in Kotlin that provides an easy to use DSL (Domain Specific Language) for transforming JSON to JSON, XML to JSON, POJ

Andrei Ciobanu 59 Sep 17, 2022
Convert Java to JSON. Convert JSON to Java. Pretty print JSON. Java JSON serializer.

json-io Perfect Java serialization to and from JSON format (available on Maven Central). To include in your project: <dependency> <groupId>com.cedar

John DeRegnaucourt 303 Dec 30, 2022
High performance JVM JSON library

DSL-JSON library Fastest JVM (Java/Android/Scala/Kotlin) JSON library with advanced compile-time databinding support. Compatible with DSL Platform. Ja

New Generation Software Ltd 835 Jan 2, 2023
JSON to JSON transformation library written in Java.

Jolt JSON to JSON transformation library written in Java where the "specification" for the transform is itself a JSON document. Useful For Transformin

Bazaarvoice 1.3k Dec 30, 2022
Generate Java types from JSON or JSON Schema and annotates those types for data-binding with Jackson, Gson, etc

jsonschema2pojo jsonschema2pojo generates Java types from JSON Schema (or example JSON) and can annotate those types for data-binding with Jackson 2.x

Joe Littlejohn 5.9k Jan 5, 2023
Essential-json - JSON without fuss

Essential JSON Essential JSON Rationale Description Usage Inclusion in your project Parsing JSON Rendering JSON Building JSON Converting to JSON Refer

Claude Brisson 1 Nov 9, 2021
Source code of APK-Explorer-Editor (AEE), an open-source tool to explore the contents of an installed APK!

APK Explorer & Editor (AEE) APK Explorer & Editor, an open-source tool to explore the contents of an installed APK, is strictly made with an aim to in

APK Explorer & Editor 271 Jan 8, 2023
Text Object Java Objects (TOJOs): an object representation of a multi-line structured text file like CSV

It's a simple manager of "records" in a text file of CSV, JSON, etc. format. It's something you would use when you don't want to run a full database,

Yegor Bugayenko 19 Dec 27, 2022
Parser of the table of contents file of the 1C platform syntax helper

Парсер файла оглавления синтакс-помощника платформы 1С Что делает? Парсит вот это: Оглавление представляет собой файл без расширения, лежит в файле sh

null 9 Jan 27, 2022
JBehave is a BDD framework for Java and all JVM languages

JBehave is a BDD framework for Java and all JVM languages (Groovy, Kotlin, Ruby, Scala).

null 23 Oct 26, 2022
A Java serialization/deserialization library to convert Java Objects into JSON and back

Gson Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to a

Google 21.7k Jan 8, 2023
High-performance JSON parser

HikariJSON A High-performance JSON parser. HikariJSON is targeted exclusively at Java 8. If you need legacy support, there are several decent librarie

Brett Wooldridge 454 Dec 31, 2022
Screaming fast JSON parsing and serialization library for Android.

#LoganSquare The fastest JSON parsing and serializing library available for Android. Based on Jackson's streaming API, LoganSquare is able to consiste

BlueLine Labs 3.2k Dec 18, 2022
A modern JSON library for Kotlin and Java.

Moshi Moshi is a modern JSON library for Android and Java. It makes it easy to parse JSON into Java objects: String json = ...; Moshi moshi = new Mos

Square 8.7k Dec 31, 2022
A fast JSON parser/generator for Java.

fastjson Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON str

Alibaba 25.1k Dec 31, 2022
JSON query and transformation language

JSLT JSLT is a complete query and transformation language for JSON. The language design is inspired by jq, XPath, and XQuery. JSLT can be used as: a q

Schibsted Media Group 510 Dec 30, 2022
Sawmill is a JSON transformation Java library

Update: June 25, 2020 The 2.0 release of Sawmill introduces a breaking change to the GeoIpProcessor to comply with the updated license of the MaxMind

Logz.io 100 Jan 1, 2023
Compare JSON in your Unit Tests

JsonUnit JsonUnit is a library that simplifies JSON comparison in tests. APIs AssertJ integration Hamcrest matchers Spring MVC assertions Spring WebTe

Lukáš Křečan 719 Dec 29, 2022
Genson a fast & modular Java <> Json library

Genson Genson is a complete json <-> java conversion library, providing full databinding, streaming and much more. Gensons main strengths? Easy to use

null 212 Jan 3, 2023