From dd8dad4ecd140405c05591e3100c69a8e4e16c51 Mon Sep 17 00:00:00 2001 From: trobro Date: Sat, 14 Oct 2023 17:31:21 +0200 Subject: [PATCH] Better JSON output formatting and testing (#35) --- src/main/org/hjson/JsonWriter.java | 15 +++++---------- src/test/org/hjson/test/Main.java | 9 +++------ 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/src/main/org/hjson/JsonWriter.java b/src/main/org/hjson/JsonWriter.java index 8d73c7f..20eb877 100644 --- a/src/main/org/hjson/JsonWriter.java +++ b/src/main/org/hjson/JsonWriter.java @@ -46,7 +46,6 @@ public void save(JsonValue value, Writer tw, int level) throws IOException { switch (value.getType()) { case OBJECT: JsonObject obj=value.asObject(); - if (obj.size()>0) nl(tw, level); tw.write('{'); for (JsonObject.Member pair : obj) { if (following) tw.write(","); @@ -56,8 +55,7 @@ public void save(JsonValue value, Writer tw, int level) throws IOException { tw.write("\":"); //save(, tw, level+1, " ", false); JsonValue v=pair.getValue(); - JsonType vType=v.getType(); - if (format && vType!=JsonType.ARRAY && vType!=JsonType.OBJECT) tw.write(" "); + if (format) tw.write(" "); if (v==null) tw.write("null"); else save(v, tw, level+1); following=true; @@ -68,17 +66,14 @@ public void save(JsonValue value, Writer tw, int level) throws IOException { case ARRAY: JsonArray arr=value.asArray(); int n=arr.size(); - if (n>0) nl(tw, level); tw.write('['); for (int i=0; i 0) tw.write(","); JsonValue v=arr.get(i); - JsonType vType=v.getType(); - if (vType!=JsonType.ARRAY && vType!=JsonType.OBJECT) nl(tw, level+1); - save(v, tw, level+1); - following=true; + nl(tw, level+1); + save(arr.get(i), tw, level+1); } - if (following) nl(tw, level); + if (n > 0) nl(tw, level); tw.write(']'); break; case BOOLEAN: diff --git a/src/test/org/hjson/test/Main.java b/src/test/org/hjson/test/Main.java index c18a778..ea52c8d 100644 --- a/src/test/org/hjson/test/Main.java +++ b/src/test/org/hjson/test/Main.java @@ -43,16 +43,13 @@ private static boolean test(String name, String file, boolean inputCr, boolean o String data1=data.toString(Stringify.FORMATTED); String hjson1=data.toString(Stringify.HJSON); if (!shouldFail) { - JsonValue result=JsonValue.readJSON(load(name+"_result.json", inputCr)); + String json2 = load(name+"_result.json", outputCr); + JsonValue result=JsonValue.readJSON(json2); String data2=result.toString(Stringify.FORMATTED); String hjson2=load(name+"_result.hjson", outputCr); if (!data1.equals(data2)) return failErr(name, "parse", data1, data2); if (!hjson1.equals(hjson2)) return failErr(name, "stringify", hjson1, hjson2); - - if (isJson) { - String json1=data.toString(), json2=JsonValue.readHjson(text, opt).toString(); - if (!json1.equals(json2)) return failErr(name, "json chk", json1, json2); - } + if (!data1.equals(json2)) return failErr(name, "JSON stringify", data1, json2); } else return failErr(name, "should fail", null, null); }