Getting json by DWR (Direct Web Remoting)

2019-08-23 15:00发布

问题:

I want to know how can I convert a Java object to JSON by using DWR. I have already tried

JsonUtil.toJson(myObject), but it gives a NullPointerException at org.directwebremoting.json.JsonUtil.toJson(JsonUtil.java:127). Can anyone tell me any way of converting the Java Object to JSON? I would prefer achieving it by DWR.

回答1:

Why not use the JSON library itself? JSON

Or even the Google-Gson Library GSON

Also, for further reference, use the Search, since similar questions to this one have been answered...

a few examples:

https://stackoverflow.com/questions/338586/a-better-java-json-library

Converting JSON to Java



回答2:

You should read the documentation as DWR has a tool that creates Json <-> Java mapping automatically. In fact that is the main purpose of DWR!



回答3:

Lets consider this java class.

       class Employee
       {
          int id;
          String eName;
           // setters and getters                
       }   

In javascript JSON object

       var employee = {
                       id   : null,
                       name : null
                      };

This is the call to java method from javascript function.

       EmployeeUtil.getRow(employee,dwrData);

In getRow() of EmployeeUtil class, return type of method will be Employee.

       Employee getRow();

So using the setters of Employee set the data.

dwrData is the callback function.

       function dwrData(data) {
                                employee=data;                   
                              }

The data returned which is Employee bean will be in callback function.

Just initialize this in javascript JSON object.

Hope this helps ....



标签: java json dwr