Lean JSON Library for Java, with a compact, elegant API.

Related tags

JSON mjson
Overview

mJson is an extremely lightweight Java JSON library with a very concise API. The source code is a single Java file. The license is Apache 2.0. Because of its tiny size, it's well-suited for any application aiming at a small footprint such as mobile/Android applications.

It was originally developed in the context of the OpenCiRM project. There is a graph database based persistent layer for mJson implemented at the HyperGraphDB Project. This means you can transparently persist and query JSON documents like in document-oriented databases (MongoDB, CouchDB), but you don't have split documents into separate collection or create special purposes indices since all documents and properties are automatically interlinked.

Features

  • Full support for JSON Schema Draft 4 validation
  • Single universal type - everything is a Json, no type casting
  • Single factory method, no new operators, just call Json.make(anything here)
  • Fast, hand-coded parsing
  • Designed as a general purpose data structure for use in Java
  • Parent pointers and up method to traverse the JSON structure
  • Concise methods to read (Json.at), modify (Json.set, Json.add), duplicate (Json.dup), merge (Json.with)
  • Methods for type-check (e.g. Json.isString()) and access to underlying Java value (e.g. Json.asString())
  • Method chaining
  • Pluggable factory to build your own support for arbitrary Java<->Json mapping
  • 1 Java file is the whole library with no external dependencies

API Tour

Go see a Complete Tour of the API

Read my tutorial blog on JSON Schema

Wish List

(get in touch if you want to help!)

  1. Traversal API, with pattern-matching
  2. Extend JSON Schema support for template generation

Goto mJson Official Website

Comments
  • Throw MJsonException only.

    Throw MJsonException only.

    ^^ Reasoning for single exception: it makes sense to have one specific exception to catch when invoking tiny specialized library. ^^

    Exception handling changes:

    • added MJsonException
    • throw MJsonException (also unchecked exception) instead of RuntimeException, when mJson encounters error condition it cannot handle and that is not illegal argument / unsupported operation exception.
    • replaced dangerously empty catch (Throwable t) {} clause with normal handling of IOException
    • throw MJsonException instead of IllegalArgumentException
    • throw MJsonException instead of UnsupportedOperationException

    Additionally:

    • addressed build warnings about pom.xml deprecated ${groupId}+ ${artifactId} references which were replaced with current ${project.etc} syntax (Maven 3.2.2 warning)
    opened by unserializable 9
  • overlay method

    overlay method

    Not sure if a great idea, but an 'overlay' or 'overwrite' method would behave sort of like 'with', except recursively it will perform a merge (actually maybe 'merge' is a better name for such a method then): if A is overlaid over B, all properties in A that are not in B will be copied to B and also all properties in A that are also in B will replace B's values. But because this is done recursively, we may have nested properties deep in B's structure be preserved instead of just disappearing.

    So this is essentially a recursive "with". While "with" overwrite blindly, a recursive with does a deep merging.

    I've only seen the need for this popup very rarely though.

    opened by bolerio 8
  • Find a json objects key in the parent json

    Find a json objects key in the parent json

    I have several cases where I have the json element in a hierarchy (eg after an event has occurred) but I need to know its key in the parent json. Basically I need to recurse the path back to the top level. This is remarkably hard to do efficiently! Ive considered several possibilities:

    1. Use google guava BiMap instead of HashMap in the ObjectJson. Then use .inverse() to find the key. Would work but BiMap must have unique values (a Set), and I suspect that will cause trouble
    2. store the key in the child object when the child is created. Also works but needs care or it causes bugs when serialising or when making misc changes like moving parent.
    3. store a ref to the parent key in the child somehow - much like 2)
    4. iterate the keys in the parent looking for an equals() match on the associated value - nice, but is it efficient in a big parent? What about two separate keys with the same value? - the BiMap problem.

    Any ideas?

    wontfix 
    opened by rob42 6
  • Support for functional equals

    Support for functional equals

    Persistable json objects usually carry some kind of technical identifier with them. Is there some way to compare two json objects without technical properties?

    For example: {"id":"1","type":"car","model":"Ferrari","color":"red"} {"id":"2","type":"car","model":"Ferrari","color":"red"}

    Both objects represent the same car (functional equality) but they are not equal/identical because of their different IDs. If there would be a way to exclude/ignore certain properties during the equals operation would be a great feature. Maybe the API could look something like car1.functionalEquals(car2,"id"); whereas the last argument is a variable parameter list. Or maybe it would be better to mark technical properties within the interal data structure of mjson itself for beeing able to handle nested/more complex objects. This would require some API for marking properties as beeing "excluded" from the functional equals comparison.

    opened by leolux 5
  • Why json.at() returns null instead of an object?

    Why json.at() returns null instead of an object?

    The following code produces a NullPointerException:

    Json json = Json.object();
    String value = json.at("notAvailable").asString();
    

    What is the advantage of json.at("...") returning null instead of a json object? I would have expected the java null value from the asString() method.

    The method Json.read() for example will never return the actual Java null. Could this also be done for the method json.at("...")?

    opened by leolux 5
  • Not serializable

    Not serializable

    I integrated mjson inside a JSF web application and it requires the Json instances to be serializable: java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: mjson.Json$ObjectJson

    The issue may be solved by adding "implements Serializable" to the objects ArrayJson, BooleanJson, NullJson, NumberJson, ObjectJson and StringJson. What do you think?

    opened by leolux 4
  • Plug-In mechanism missing for mapping from java.util.Date to Json

    Plug-In mechanism missing for mapping from java.util.Date to Json

    As stated in the javadoc of the interface Json.Factory the method make(Object) allows me to plug-in my own mapping of java.util.Date to Json. But how to achive this without reimplementing the whole method?

    Futhermore I would like to know if it is possible to globally map the other way around from a Json string to java.util.Date. I would have expected something like Json.asDate() or Json.asType(Class type) for the conversion to Java instances.

    opened by leolux 3
  • add support of JSONPath

    add support of JSONPath

    Seems pretty advance and nice:

    https://code.google.com/p/json-path/

    Since Spring framework is adopting it, probably it's going to gain industry acceptance, and there's nothing else like it.

    opened by bolerio 3
  • Schema with $ref in spring resource file and NPE

    Schema with $ref in spring resource file and NPE

    1. I have my schema file in src/main/resources
    2. In schema i have construction like "$ref": "#/definitions/deleteSchema"
    3. I open schema ResourceLoader resourceLoader ; .... Json.Schema schema = Json.schema(resourceLoader.getResource("classpath:" + jsonSchemaFile).getURI());
    4. I have NPE
    Caused by: java.lang.RuntimeException: java.lang.NullPointerException
            at mjson.Json$DefaultSchema.<init>(Json.java:1009) ~[mjson-1.3.jar:na]
            at mjson.Json.schema(Json.java:1035) ~[mjson-1.3.jar:na]
            ... 48 common frames omitted
    Caused by: java.lang.NullPointerException: null
            at mjson.Json.resolveRef(Json.java:462) ~[mjson-1.3.jar:na]
            at mjson.Json.expandReferences(Json.java:508) ~[mjson-1.3.jar:na]
            at mjson.Json.expandReferences(Json.java:529) ~[mjson-1.3.jar:na]
            at mjson.Json.expandReferences(Json.java:519) ~[mjson-1.3.jar:na]
            at mjson.Json$DefaultSchema.<init>(Json.java:1006) ~[mjson-1.3.jar:na]
    
    opened by Jacuo 2
  • Bad order in toString()

    Bad order in toString()

    Hi,

    I'm trying to convert JSON from/to String as follows:

        String myJSONString = "{\"user\":\"myuser\",\"pw\":\"mypass\",\"log\":true}";
        System.out.println(myJSONString);
        Json json = Json.read(myJSONString);
        System.out.println(json.toString());
    

    That is, I expect that myJSONString.equals(json.toString()) returns true, but it does not.

    The values that System.out.println() show are:

    {"user":"myuser","pw":"mypass","log":true} {"log":true,"pw":"mypass","user":"myuser"}

    For myJSONString and json.toString(), respectively. Therefore, json.toString() inverts the string. Is this a bug? I want to load/store the same JSON string from/to disk several times but due to this behaviour I'm not able to do that.

    PS: The problem is that next time I load the MyJSONString from this it cannot be validated using the JSON schema.

    wontfix 
    opened by manolodd 2
  • Make Junit test-scoped

    Make Junit test-scoped

    Junit is currently deployed to Maven Central with scope compile, which isn't necessary and requires end users to exclude it as a transitive dependency. It's also licensed under EPL, which could confuse people who see that mjson is licensed under Apache 2.

    opened by rjenkinsjr 1
  • Release 1.4 includes Junit as a dependency

    Release 1.4 includes Junit as a dependency

    The current release of MJSON (1.4.1) includes junit as a dependency in it's pom. This is surprising since it promises to have no dependencies. I see that it's actually been fixed in master but no new version has been released since 2017.

    opened by lbergelson 0
  • Pretty print json

    Pretty print json

    Hey , is it possible to pretty print Json as a string ? For now I found only 2 toString methods(default one and one with maxCharacters) and non of them is able to pretty print Json object

    opened by strogiyotec 0
  • Update Object to use LinkedHashMap rather than HashMap

    Update Object to use LinkedHashMap rather than HashMap

    Updated HashMap usages to use LinkedHashMap to preserve order of key insertion in Objects.

    AFAIK this is not part of the spec yet makes the behavior consistent with other JSON parsers: 1 2 3 4

    opened by arkban 0
  • bug in object delAt

    bug in object delAt

    		public Json delAt(String property) 
    		{
    			Json el = object.remove(property);
    			removeParent(el, this);
    			return this;
    		}
    

    when there is no value for the property being deleted, the removeParent call leads to an NPE

    opened by bolerio 0
  • toString should produce parsable JSON by default

    toString should produce parsable JSON by default

    The current default implementation of Json.toString will output an ellipsis (...) when the traversal is about to output the same object (same Java reference). This is to avoid circularity issues and because the aim of toString was for display purposes. We might break backward compatibility (and maybe this can be made optional), but this decision is a bit counter-intuitive. One expected toString to at least produce a valid JSON string. Because we set out to support graphs in this API and not just trees, we have to handle circular structures. But we can do this in a separate method, e.g. displayString or some such. Alternatively, we could offer a hook to be provided by the user to deal with serializing the same object, but in a different context.

    opened by bolerio 0
Owner
Borislav Iordanov
Borislav Iordanov
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
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
A simple java JSON deserializer that can convert a JSON into a java object in an easy way

JSavON A simple java JSON deserializer that can convert a JSON into a java object in an easy way. This library also provide a strong object convertion

null 0 Mar 18, 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
A 250 lines single-source-file hackable JSON deserializer for the JVM. Reinventing the JSON wheel.

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-n

Roman Böhm 14 Jan 4, 2023
Elide is a Java library that lets you stand up a GraphQL/JSON-API web service with minimal effort.

Elide Opinionated APIs for web & mobile applications. Read this in other languages: 中文. Table of Contents Background Documentation Install Usage Secur

Yahoo 921 Jan 3, 2023
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
A universal types-preserving Java serialization library that can convert arbitrary Java Objects into JSON and back

A universal types-preserving Java serialization library that can convert arbitrary Java Objects into JSON and back, with a transparent support of any kind of self-references and with a full Java 9 compatibility.

Andrey Mogilev 9 Dec 30, 2021
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
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
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
JSON Library for Java with a focus on providing a clean DSL

JSON Library for Java with a focus on providing a clean DSL

Vaishnav Anil 0 Jul 11, 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
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 JSON Transmission Protocol and an ORM Library for automatically providing APIs and Docs.

?? 零代码、热更新、全自动 ORM 库,后端接口和文档零代码,前端(客户端) 定制返回 JSON 的数据和结构。 ?? A JSON Transmission Protocol and an ORM Library for automatically providing APIs and Docs.

Tencent 14.4k Dec 31, 2022
Jakarta money is a helpful library for a better developer experience when combining Money-API with Jakarta and MicroProfile API.

jakarta-money Jakarta money is a helpful library for a better developer experience when combining Money-API with Jakarta and MicroProfile API. The dep

Money and Currency API | JavaMoney 19 Aug 12, 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
A reference implementation of a JSON package in Java.

JSON in Java [package org.json] Click here if you just want the latest release jar file. Overview JSON is a light-weight language-independent data int

Sean Leary 4.2k Jan 6, 2023