Skip to content

Commit

Permalink
3.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
miktim committed Oct 16, 2024
1 parent 1bda4cb commit ae7cf1d
Show file tree
Hide file tree
Showing 7 changed files with 255 additions and 47 deletions.
97 changes: 93 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,19 @@ Cast Java object by sample
**static <T\> T cast(Object obj, Class <T\> cls) throws ClassCastException**
Cast Java object by class


```
int[] ints;
ints = JSON.castTo(JSON.fromJSON("[1.2, 3.4, 5.6]", int[].class);
// ints contains int[]{1, 3, 5}
String s = JSON.toJSON(ints, 2);
/* s contains
"[
1,
3,
5
]"
*/
```
### Class Json extends HashMap <String, Object\>
This class is a Java representation of a JSON object.
Json member types:
Expand Down Expand Up @@ -82,7 +94,16 @@ Create Json object from String

**Json(InputStream inStream) throws IOException, ParseException**
Create Json object from UTF-8 encoded stream.

```
// create Json object from name, value pairs
Json j = new Json("number", 1, "string", "qwerty", "boolean", true);
String s = j.toJSON();
/* s contains
"{\"number\": 1, \"string\": \"qwerty\", \"boolean\": true}"
*/
// create Json object from String
j = new Json("{ \"number\": 1, \"string\": \"qwerty\", \"boolean\": true }");
```
<p style="background-color: #B0C4DE;">
&emsp;<b>Methods:</b>
</p>
Expand Down Expand Up @@ -143,6 +164,14 @@ Stringify member value or array element as single line

**Json toJSON(OutputStream outStream) throws IOException**
OutStream is UTF-8 encoded single line JSON text. Returns this
```
// another way to create a Json object
Json j = (new Json()).set("personId", 1234).set("firstName","John")
.set("phones", new String[]{"123-4567","890-1234"});
String[] phones = new String[];
// get an array of phones
phones = j.castMember("phones", phones);
```


### Abstract Class JsonObject
Expand Down Expand Up @@ -199,8 +228,68 @@ Overridden. Generate JSON text as a single line
**static boolean isClassName(String name);**

**protected &lt;T\> T castMember(String memberName, Json jsonObj, T sample);**
Returns the sample if Json member does not exists or is null

Returns the sample if Json member does not exists or is null

```
public class Person extends JsonObject {
int personId = 0;
String firstName = "";
String lastName = "";
boolean married = false;
HashMap<String, String> phones = new HashMap<>();
// default constructor
public Person() {
}
@Override
protected Object replacer(String name, Object value) {
if(name.endsWith(".phones")) {
// unload phones Map
Json json = new Json();
for (Map.Entry<String, String> entry : phones.entrySet()) {
json.set(entry.getKey(), entry.getValue());
}
return json;
}
return value;
}
@Override
protected Object reviver(String name, Object value) {
if (name.endsWith(".phones")) {
// load phones Map
phones.clear(); // fill existing Map
Json json = (Json) value;
for (String key : json.listNames()) {
phones.put(key, json.getString(key));
}
return IGNORED; // phones already loaded
}
return value;
}
}
public static void main(String[] params)
throws IllegalArgumentException, IllegalAccessException,
IOException, ParseException {
// create and fill Person object
Person person = new Person();
person.personId = 12345;
person.firstName = "John";
person.lastName = "Doe";
person.phones.put("home", "123-4567");
person.phones.put("work", "789-0123");
// unload person to string
String s = person.toJson().toJSON();
System.out.println(s);
/* console output
{ "personId": 12345, "fistName": "John", "lastName": "Doe", "married": false, "phones": { "home": "123-4567", "work": "789-0123" }
*/
// load person from string
person = (new Person()).fromJson(new Json(s));
}
```

**See usage here:**
./test/json/JsonTest.java
Expand Down
Binary file modified dist/json-3.0.0.jar
Binary file not shown.
4 changes: 2 additions & 2 deletions src/org/miktim/json/JSONGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ void generateObject(Object value, int level) throws IOException {
generateObject(String.valueOf(value), level);
}

private static final int[] UNESCAPED_CHARS = {0x8, 0x9, 0xA, 0xC, 0xD, 0x22, 0x5C}; // {0x8, 0x9, 0xA, 0xC, 0xD, 0x22, 0x2F, 0x5C}
private static final String[] CHARS_ESCAPED = {"\\b", "\\t", "\\n", "\\f", "\\r", "\\\"", "\\\\"}; // {"\\b", "\\t", "\\n", "\\f", "\\r", "\\\"", "\\/", "\\\\"}
private static final int[] UNESCAPED_CHARS = {0x8, 0x9, 0xA, 0xC, 0xD, 0x22, 0x2F, 0x5C};
private static final String[] CHARS_ESCAPED = {"\\b", "\\t", "\\n", "\\f", "\\r", "\\\"", "\\/", "\\\\"};

static String escapeString(String s) {
StringBuilder sb = new StringBuilder(64);
Expand Down
4 changes: 2 additions & 2 deletions src/org/miktim/json/Json.java
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@ public <T> T castMember(Class<T> cls, String memberName, int... indices) {
return JSON.cast(get(memberName, indices), cls);
}

public Json normalize() throws Exception {
return (Json) JSON.fromJSON(toString()); // :)
public Json normalize() throws IOException, ParseException {
return (Json) JSON.fromJSON(this.toString()); // :)
}

}
73 changes: 34 additions & 39 deletions src/org/miktim/json/JsonObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,39 @@
*/
package org.miktim.json;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedHashMap;

public abstract class JsonObject {
public abstract class JsonObject {

public final Json toJson()
public final Json toJson()
throws IllegalArgumentException, IllegalAccessException {
return unload(this, this);
}

@SuppressWarnings("unchecked")
public final <T> T fromJson(Json json)
public final <T> T fromJson(Json json)
throws IllegalArgumentException, IllegalAccessException {
return (T) load(this, this, json);
}

public final <T> T fromJson(T target, Json json)
public final <T> T fromJson(T target, Json json)
throws IllegalArgumentException, IllegalAccessException {
return (T) load(this, target, json);
}

public final Json toJson(Object target)
public final Json toJson(Object target)
throws IllegalArgumentException, IllegalAccessException {
return unload(this, target);
}

@Override
public String toString() {
try {
return toJson().toString();
} catch (IllegalArgumentException | IllegalAccessException ex) {
return JSON.toJSON(toJson());
} catch (IllegalArgumentException | IllegalAccessException | IOException ex) {
ex.printStackTrace();
}
return null;
Expand All @@ -54,7 +55,6 @@ public String toString() {

@SuppressWarnings("unchecked")
protected <T> T getTarget() {
// Class<T> cls = (Class<T>) target.getClass();
return (T) target;
}

Expand All @@ -65,11 +65,13 @@ protected Object replacer(String name, Object value) {
protected Object reviver(String name, Object value) {
return value;
}
/*

/*
protected void onError(String name, Exception e) {
System.err.println(name + " " + e.getMessage());
}
*/
*/

@SuppressWarnings("unchecked")
protected <T> T castMember(String memberName, Json jsonObj, T sample) {
if (jsonObj.get(memberName) != null) {
Expand Down Expand Up @@ -99,6 +101,7 @@ boolean isJsonType(Object obj) {
|| c.isArray() && c.getComponentType().isPrimitive();
}
*/

Json unload(JsonObject thisObj, Object targetObj) //{// returns Object
throws IllegalArgumentException, IllegalAccessException {
if (targetObj instanceof JsonObject) {
Expand All @@ -117,21 +120,15 @@ Json unload(JsonObject thisObj, Object targetObj) //{// returns Object
String fieldName = field.getName();
// if (!thisObj.isIgnored(fieldName)) continue;
field.setAccessible(true);
// try {
Object value = thisObj.replacer(fieldName(field),
field.get(targetObj));
if (value == null || !value.equals(IGNORED)) {
if (value instanceof JsonObject) {
value = unload(thisObj, value);
}
((Json) json).set(fieldName, value);
Object value = thisObj.replacer(fieldName(field),
field.get(targetObj));
if (value == null || !value.equals(IGNORED)) {
if (value instanceof JsonObject) {
value = unload(thisObj, value);
}
// } catch (Exception ex) {
// thisObj.onError(fieldName(field), ex);
// System.err.println(e.getMessage());
// }
((Json) json).set(fieldName, value);
}
}

this.target = oldTarget; // restore target object
return (Json) json;//.normalize(); //???
}
Expand All @@ -148,6 +145,7 @@ <T> T loadArray(JsonObject thisObj, T value, Object newValue) {
return (T) array;
}
*/

<T> T load(JsonObject thisObj, T targetObj, Object json) //{
throws IllegalArgumentException, IllegalAccessException {
if (targetObj instanceof JsonObject) {
Expand All @@ -163,22 +161,19 @@ <T> T load(JsonObject thisObj, T targetObj, Object json) //{
// if (thisObj.isIgnored(fieldName) continue;
if (((Json) json).exists(fieldName)) {
field.setAccessible(true);
// try {
Object newValue = thisObj.reviver(fieldName(field),
((Json) json).get(fieldName));
Object value = field.get(targetObj);
if ((field.getModifiers() & Modifier.FINAL) == 0
&& (newValue == null || !newValue.equals(IGNORED))) {
if (value != null && value instanceof JsonObject) {
field.set(targetObj, load(thisObj, value, newValue));
} else {
field.set(targetObj, JSON.cast(newValue, value));
}
Object newValue = thisObj.reviver(fieldName(field),
((Json) json).get(fieldName));
Object value = field.get(targetObj);
if ((field.getModifiers() & Modifier.FINAL) != 0) {
continue;
}
if ((newValue == null || !newValue.equals(IGNORED))) {
if (value != null && value instanceof JsonObject) {
field.set(targetObj, load(thisObj, value, newValue));
} else {
field.set(targetObj, JSON.cast(newValue, value));
}
// } catch (Exception ex) {
// thisObj.onError(fieldName(field), ex);
// System.err.println(ex.getMessage());
// }
}
}
}
}
Expand All @@ -205,7 +200,7 @@ private Field[] getAccessibleFields(Object thisObj, Object targetObj) {
continue;
}
// for different package public and protected fields
if (clsPkg != thisPkg
if (clsPkg != thisPkg
&& (field.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0) {
continue;
}
Expand Down
Loading

0 comments on commit ae7cf1d

Please sign in to comment.