• k8_207384
  • 172.7KB
  • zip
  • 0
  • VIP专享
  • 0
  • 2022-06-14 05:01
    上传日期,在Java中以“适当”的方式使用JSON的框架。没有映射或模型类,它只是可爱的JSON,但在Java中。一个操作JSON数据结构的流畅Java API
[![Build Status](]( [![JitPack](]( # Introduction JsonJ is a fast performing addon library to Jackson for working with schemaless [json]( in Java. JsonJ backs the very simple json types using a fluent API. Jackson's streaming parser is used for parsing and it uses things like generics, Java 8 streams, varargs, the Collections framework and other modern Java constructs to make life easier dealing with json. As of 2.43, JsonJ also fully supports the Jackson ObjectMapper. Simply use the jsonj types (`JsonObject`, `JsonArray`, and `JsonPrimitive`) and jackson will serialize/deserialize as you are used to. So you can mix jsonj objects this with using strongly typed model classes. The core use case for jsonj is quickly prototyping with complex json data structures without getting bogged down in creating endless amounts of model classes. Model classes are nice if you have a stable, and well defined domain but can be a royal pain in the ass when this is not the case and your json is relatively complex and more or less schema less. # Get JsonJ After lots of frustration babysitting maven central deploys; we now release instantly on jitpack: [![JitPack](]( Older releases may still be available on maven central. If a recent release on maven central is critical to you, ping me. Note. always check for the latest version. I do not always update the readme. Java 8 is required as of version 2. For Java 7 and earlier, you can use the 1.x releases. # License The license is the [MIT license](, a.k.a. the expat license. The rationale for choosing this license is that I want to maximize your freedom to do whatever you want with the code while limiting my liability for the damage this code could potentially do in your hands. I do appreciate attribution but not enough to require it in the license (beyond the obligatory copyright notice). # Examples JsonJ has a ton of features and there's plenty more to discover beyond what is shown here. ## Parsing JsonJ uses Jackson's streaming parser with a custom handler to parse json into JsonElement instances. This is the fastest way to parse json. ``` // Create a parser (you need just 1 instance for your application) JsonParser parser = new JsonParser(); // Parse some json JsonElement element = parser.parse("[1,2,3]"); // when using streams, we assume you are using UTF-8 JsonObject object = parser.parseObject(inputStream); // or just use a reader JsonElement element = parser.parse(reader); // Jsonj also supports yaml, bson, hocon, and several other tree like syntaxes through Jackson's plugin infrastructure. // for example: YamlParser yamlParser = new YamlParser(); JsonElement anotherElement = yamlParser.parse(inputStream) ``` ## Using the Jackson ObjectMapper As of 2.43, the Jackson ObjectMapper is fully supported. ``` JsonObject myObject=...; String serialized = objectMapper.writeValueAsString(myObject); JsonObject deSerialized = objectMapper.readValue(serialized, JsonObject.class); // myObject.equals(deSerialized); ``` This also means you can mix jsonj with pojos in your models: For example, this will work as you'd hope: ``` class Foo { private String attribute; private int anotherAttribute; private JsonObject nestedJsonj; public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } public int getAnotherAttribute() { return anotherAttribute; } public void setAnotherAttribute(int anotherAttribute) { this.anotherAttribute = anotherAttribute; } public JsonObject getNestedJsonj() { return nestedJsonj; } public void setNestedJsonj(JsonObject nestedJsonj) { this.nestedJsonj = nestedJsonj; } } Foo foo = new Foo(); foo.setAttribute("Hi wrld"); foo.setAnotherAttribute(42); JsonObject nested = object( field("meaning_of_life",42), field("a",42.0), field("b",true), field("c",array(42,"foo",3.14,true,null)), field("d",object(field("a",1))) ); foo.setNestedJsonj(nested); String serialized = objectMapper.writeValueAsString(foo); JsonObject object = parser.parseObject(serialized); assertThat(object.getString("attribute")).isEqualTo("Hi wrld"); assertThat(object.getInt("anotherAttribute")).isEqualTo(42); assertThat(object.getObject("nestedJsonj")).isEqualTo(nested); // or of course Foo fooParsed = objectMapper.readValue(serialized, Foo.class); // etc. ``` ## Serializing ``` JsonObject o=parser.parse(inputStream); // Jsonj objects know how to serialize themselves String oneLine=o.toString(); // pretty printing is nice when reading json String pretty=o.prettyPrint(); // you can also serialize straight to a writer of course. o.serialize(writer); ``` ## Json manipulation ``` // easy object and array creation using simple static factory methods, varargs, and smart polymorph argument processing JsonObject o = object( field("hello","world"), field("another_field",array("of","mixed","types",42, 42.0,true,false,null)), field("nested",object(field("nested_field",42))) ); // basic element lookup JsonElement e = o.get("hello"); // JsonPrimitive with value "world" JsonElement e2 = o.get("nested"); // JsonObject JsonElement e3 = o.get("nested","nested_field"); // JsonPrimitive with value 42 // type safe value extraction Integer value = o.getInt("nested","nested_field"); // 42 Integer noValue = o.getInt("nested","idontexist"); // null Integer defaultValue = o.getInt("idontexist", 42); // null Optional<Integer> o.maybeGetInt("nested","idontexist"); // Optional.empty(); // there are several variations of these for strings, booleans, longs, doubles, floats, and Number. // convert JsonElements JsonElement e= .... int val=e.asInt(); // throws JsonTypeMismatchException if the element is not a JsonPrimitive or cannot be converted to an int. JsonObject object = e.asObject(); // throws JsonTypeMismatchException if e.isObject() == false JsonArray object = e.asArray(); // throws JsonTypeMismatchException if e.isArray() == false // on the fly nested object and array creation //creates a five level deep array at o.l1.l2.l3.l4.a1=[1,2,3] o.getOrCreateObject("l1","l2","l3").getOrCreateArray("l4","a1").add(1,2,3); // adds three more elements to the array o.getOrCreateObject("l1","l2","l3").getOrCreateArray("l4","a1").add(4,5,6); ``` ## Collections ``` // objects are Map<String,JsonElement> // so this works, as well as all of the Map API in java 8. object.forEach((key,element) -> {...}); // easy iteration over entries in the Map<String,JsonElement) // likewise, JsonArray implements List<JsonElement> // so you can do stream processing JsonArray result = object.getOrCreateArray("array").stream().map(element -> element.asObject().getString("nested_field")).collect(JsonJCollectors.array()); // Java has sets and they are useful, JsonSet implements Set<Element> // asSet converts the list to a set and removes duplicate elements // inserts of duplicate elements replace the old value JsonSet set = object.getOrCreateArray("array").asSet(); // by default JsonSet uses element equals for identity but you can change this JsonSet set2 = object.getOrCreateArray("array") .asSet() // return true if left and right elements are equal, false otherwise); .applyIdStrategy((left,right) -> ...); // or use the simple id field strategy for the common case where you // have an array of objects with an id field // compares objects on their id field, throws JsonTypeMismatchException // if elements are not objects. JsonSet set3 = object.getOrCreateArray("array").asSet().applyIdStrategy("id"); ``` ## Polymorphism and varar