A Java library for JSON

XGG Blog

https://github.com/CyberZHG/JJson

JJson is used for parsing or generating JSON strings.

Introduction

This is a Java library which aimed at parsing or generating JSON strings. In the parsing phase, the format of the JSON string is strictly examined, thus an invalid JSON string will not parsed to any JSON element. The generated JSON strings will have no extra whitespace characters.

Parse JSON StringJsonValue json = new JsonValue();String jsonString = “{\”string\”:\”string\”,\”number\”:-12.3,\”true\”:true,\”false\”:false,\”null\”:null}”;if (json.tryParse(jsonString)) {// Now json contains the JSON structure.} else {// The format of JSON string is invalid.}Generate JSON StringJsonObject obj = new JsonObject();obj.putValue(“string”, new JsonString(“1”));obj.putValue(“number”, new JsonNumber(2));obj.putValue(“object”, new JsonObject());obj.putValue(“array”, new JsonArray());obj.putValue(“boolean”, new JsonBoolean(true));obj.putValue(“null”, new JsonNull());System.out.println(obj.toString());// Print: {“array”:[],”boolean”:true,”null”:null,”number”:2,”object”:{},”string”:”1″}JsonArray obj = new JsonArray();obj.addValue(new JsonValue(“1”));obj.addValue(new JsonValue(2));obj.addValue(new JsonObject());obj.addValue(new JsonArray());obj.addValue(new JsonValue(true));obj.addValue(new JsonValue());System.out.println(obj.toString());// Print: [“1”,2,{},[],true,null]JSON ElementsJsonValue

JsonValue is the parent class of six JSON value types, which are JsonString, JsonNumber, JsonObject, JsonArray, JsonBoolean and JsonNull.

If the structure of the JSON string to be parsed is unknowned, it is recommended to use JsonValue to parse the string. There is a private variable data in JsonValue which belongs to the six JSON value types mentioned above. Then the getter functions (e.g. String getString(), double getNumber(), Map<JsonString, JsonValue> getObject(), List<JsonValue> getArray(), boolean getBoolean()) could be used to expolore the inner structure of the JSON element.

JsonString

JsonNumber

Due to the design of number in JavaScript, the type of the number data is double. The generated JSON string will be an integer (e.g. 12 instead of 12.0) if the decimal part contains only zero.

JsonObject

The key-value pairs are stored in SortedSet<JsonString, JsonValue>, thus the keys in the generated JSON string is sorted in lexicographic order. If the JSON string contains duplicated keys then it is not recognized as a valid JSON format.

JsonArray

The values in the array are stored in List<JsonValue>.

AcknowledgementIntroducing JSON

,爬上那座山,听最圣洁的经。

A Java library for JSON

相关文章:

你感兴趣的文章:

标签云: