The package is for JSON conversion in Java enviroment.
| JSON Type | JSON Type Example | Java Type |
|---|---|---|
| object | {} | JSONObject |
| array | [] | JSONArray |
| string | "example" | String |
| number | 1/1.0 | BigInteger/BigDecimal |
| "true" | true | boolean |
| "false" | false | boolean |
| "null" | null | null |
Convert a JSON string into a JSON object
JSON.parse(value) is based on stack structure.
There are three stacks in the program, stack stack for characters, class_stack stack for list and dict, keyvalue_stack stack for name/value pair.
Scan each character in the string, do the following:
- If is
[, put type/value intoclass_stackstack - If is
{, put type/value into theclass_stackstack, and put an empty key/value pair (namedborder) into thekeyvalue_stackstack - If is
,, according toclass_stackstack top type (list and dict),listis to operate on the top of theclass_stackstack and call its append method,dictis pushed into thekeyvalue_stackstack - If is
], popping all the elements on the top of thestackstack until it encounters[ - If is
}, pop thekeyvalue_stackstack and pop all the elements on the top of the stack until it encountersborder - If is
:, operate on the top of thekeyvalue_stackstack and modify the value in the key/value pair - Other, put characters into the
stackstack
Convert JSON values to JSON strings
JSON.stringify(value) is using recursive method.
- If it is a basic type in Python (number, string, bool, None), return the corresponding string (1/1.0, "example", true/false, null)
- If it is list and dict, repeat step 1 for each element in the list and dict
- Others, It is a class, consider as a dict type, terating over member variables of a class, do the same action as step 1
<dependency>
<groupId>com.github.myibu</groupId>
<artifactId>json4j</artifactId>
<version>1.0.0</version>
</dependency>- Convert a JSON string into a JSON object.
JSONObject jsonObject = JSONObject.parse("[\"foo\", {\"bar\": [\"baz\", null, 1.0, 2, true]}]");
// or write as following if you donot known the type of th json String
Object jo = JSON.parse("[\"foo\", {\"bar\": [\"baz\", null, 1.0, 2, true]}]");- Convert JSON values to JSON strings.
Map<String,String> map = new HashMap<>();
map.put("1", "00");
String jsonString = JSON.toJSONString(map);- Format JSON object or JSON strings
Map<String,String> map = new HashMap<>();
map.put("1", "00");
String formatedJsonString = JSON.format(map);