Google gson の fromJson や JsonParser 生成は、次のようなJSONであると
{ "A": "12", }
com.google.gson.JsonSyntaxException:
com.google.gson.stream.MalformedJsonException:
Expected name at line 3 column 2 path $.A
と例外を発生してくれます。
JSONテキストを事前にチェックする機能を考えた時、すぐに思いつくのが、、
JsonReader reader = new JsonReader(new StringReader(jsonstr)); try{ new JsonParser().parse(reader); }catch(JsonSyntaxException e){ String causemessage = Optional.ofNullable(e.getCause()) .filter(t->t instanceof MalformedJsonException).map(t->t.getMessage()) .orElse("Unknown Error"); }
↑は、JSON文字列 jsonstr が NULL でなければ、想定どおり JsonSyntaxException で catch して動くのですが、
JsonParser で parse 対象が NULLだったり、try の中の状況によっては、これはダメです。
.filter(t->t instanceof MalformedJsonException).
でいきなり限定しているのも好ましくないです。
そこで、以下のような static メソッドを用意します。
public static boolean parseFormat(String str, Consumer<String> malform , BiConsumer<Throwable, String> unknowns){ try{ JsonReader reader = new JsonReader(new StringReader(str)); new JsonParser().parse(reader); return true; }catch(JsonSyntaxException e){ Throwable cause = e.getCause(); if (cause==null){ unknowns.accept(e, e.getMessage()); }else if(cause instanceof MalformedJsonException){ malform.accept(cause.getMessage()); }else{ unknowns.accept(cause, cause.getMessage()); } }catch(Exception e){ unknowns.accept(e, e.getMessage()); } return false; }
こうすれば、、
if (parseFormat(jsonstr, m->{ // m = MalformException の getMessafe() // TODO 書式エラーの処理 }, (t, m)->{ // t = MalformExceptionでない他の Throwable // m = t の getMessage() // TODO 読込エラーの処理 })){ // JSON 文字列 jsonstr が書式で問題なく Gson fromJson を実行できる }
と整理できます。
この static メソッドを使い回せるようにしたいと思います。