Search code examples
javajsongwtjsni

How do I extract a nested JSON object using JSNI Overlay Types in GWT?


So I have this JSON object coming to me which has roughly the following format:

{   "student":{"field1":"","field2":"",....},
    "subjects":[{},{},....,{}]                     }

How do I extract the entire contents of "student" and each object in the array of "subjects" in GWT using overlay types and the JsonUtils methods?


Solution

  • The easiest way is to make a JavaScriptObject that exposes the wrapper object to Java, with getters for the student and subjects properties as other JavaScriptObject and JsArray.

    final class StudentAndSubjects extends JavaScriptObject {
      protected StudentAndSubjects() { }
    
      public native Student getStudent() /*-{ return this.student; }-*/;
      public native JsArray<Subject> getSubjects() /*-{ return this.subjects; }-*/;
    }
    
    final class Student extends JavaScriptObject {
      protected Student() { }
    
      public native String getField1() /*-{ return this.field1; }-*/;
      public native String getField2() /*-{ return this.field2; }-*/;
      …
    }
    
    final class Subject extends JavaScriptObject {
      protected Subject() { }
    
      …
    }
    

    You can then use them like this:

    StudentAndSubjects sas = JsonUtils.safeEval(json);
    Student student = sas.getStudent();
    JsArray<Subject> subjects = sas.getSubjects();
    for (int i = 0, l = subjects.length(); i < l; i++) {
      Subject subject = subjects.get(i);
      …
    }