如何将 JSON 转换为 Java 对象,反之亦然

How To Convert JSON to Java object, and vise-versa

我想用存储在数据库中的数据/事件日期填充我在 Web 视图上绘制的 FullCalendar。

我知道我必须通过 JSON 完成此操作。问题是实际上我在网上看到的所有文档都只停留在 "How To Convert JSON to Java object",反之亦然。如何使转换后的 JSON/ Java 对象在 HTML/ Java class 中可见?

例如,假设我有一个从数据库中检索到的事件/约会对象列表。

List<FullCalendarData> events = new ArrayList();

FullCalendarDataPOJOclass:

@Component
@Entity
@Table(name = "ENTITY_OBJECT")
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")

@Inheritance(strategy = InheritanceType.JOINED)
public class FullCalendarData {

    private String eventName;
    private String startTime;
    private String endTime;

    public String getEventName() {
        return eventName;
    }

    public void setEventName(String eventName) {
        this.eventName = eventName;
    }

    public String getStartTime() {
        return startTime;
    }

    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    public String getEndTime() {
        return endTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

}

List<FullCalendarData> events 从 Java 转换为 JSON:

Gson gson = new Gson();
String jsonAppointment = gson.toJson(events);

现在的问题是,如何使 jsonAppointment 在下面 HTML\ webview 的 FullCalendar 中可见,或者换句话说,我如何访问和迭代 jsonAppointment 并使用它 (jsonAppointment) 而不是下面的 events 数组?

<!DOCTYPE html>
<html>
    <head>
        <link href='../fullcalendar/fullcalendar.css' rel='stylesheet' />
        <link href='../fullcalendar/fullcalendar.print.css' rel='stylesheet' media='print' />
        <script src='../lib/jquery.min.js'></script>
        <script src='../lib/jquery-ui.custom.min.js'></script>
        <script src='../fullcalendar/fullcalendar.min.js'></script>
        <script>

            $(document).ready(function() {

                var date = new Date();
                var d = date.getDate();
                var m = date.getMonth();
                var y = date.getFullYear();

                $('#calendar').fullCalendar({
                    editable: true,
                    events: [
                        {
                            title: 'All Day Event',
                            start: new Date(y, m, 1)
                        },
                        {
                            id: 999,
                            title: 'Repeating Event',
                            start: new Date(y, m, d + 4, 16, 0),
                            allDay: false
                        }
                    ]
                });

            });

        </script>
    </head>
    <body>
        <div id='calendar'></div>
    </body>
</html>

调用我们的网络视图:

public class FullCalendarWebView {

    public VBox calendar() {
        final WebView webView = new WebView();
        final WebEngine engine = webView.getEngine();
        engine.load("file:D:/standAloneDev//src/fc/fullcalendarwebview/fullcalendar-1.6.4/demos/selectable.html");

        JSObject script = (JSObject) engine.executeScript("window");
        script.setMember("eventClick", new JavaApp().javaApp());

        VBox vb = new VBox();
        vb.getChildren().add(webView);

        return vb;
    }

}

将单个事件发送到日历

为了将一些事件从 JavaFX 发送到日历,首先您应该创建一个 JavaScript 函数来在日历上生成一个事件:

private WebView webView;
private WebEngine engine;

private void createCalendar() {
    webView = new WebView();
    engine = webView.getEngine();
    engine.load("file:D:/standAloneDev//src/fc/fullcalendarwebview/fullcalendar-1.6.4/demos/selectable.html");

    engine.getLoadWorker().stateProperty().addListener((ov,oldState, newState)->{
        if(newState==State.SUCCEEDED){

            // JS to Java
            JSObject script = (JSObject) engine.executeScript("window");
            script.setMember("myClick", new JavaApp());

            // Java to JS, function to create single event
            engine.executeScript("function addEvent(title, start, end) {\n" +
                            "var eventData = {\n" +
                            "   title: title,\n" +
                            "   start: start,\n" +
                            "   end: end\n" +
                            "};\n" +
                            "$('#calendar').fullCalendar('renderEvent', eventData, true);\n" +
                         "}");
        }
    });
}

现在我们可以在 JavaFX 应用程序上测试这个函数,用一些数据调用脚本:

@Override
public void start(Stage primaryStage) {

    Button btn=new Button("Add Event");
    btn.setOnAction(e->{
        FullCalendarData data1=new FullCalendarData();
        data1.setEventName("Event 1");
        data1.setStartTime("2015-01-11T16:00:00");
        data1.setEndTime("2015-01-11T18:00:00");
        engine.executeScript("addEvent('"+data1.getEventName()+
                             "','"+data1.getStartTime()+
                             "','"+data1.getEndTime()+"');");

    });

    createCalendar();

    Scene scene = new Scene(new VBox(webView,btn), 600, 400);
    primaryStage.setScene(scene);
    primaryStage.show();
}

将事件列表发送到日历

如果您想使用 JSON 格式发送事件列表,您可以创建另一个函数来处理列表并对列表中的每个元素调用 addEvent()

engine.getLoadWorker().stateProperty().addListener((ov,oldState, newState)->{
        if(newState==State.SUCCEEDED){
            ...
            // Java to JS, send JSON list
            engine.executeScript("function addListEvents(result) {\n" +
                            "for(var i=0; i<result.data.length; i++){\n" +
                            "   addEvent(result.data[i].eventName, result.data[i].startTime, result.data[i].endTime);\n" +
                            "};\n" +
                         "}");
        }
    });

对事件列表使用包装器:

class CalendarEvents{
    final List<FullCalendarData> data=new ArrayList<>();

    public List<FullCalendarData> getData() {
        return data;
    }

    public void addEvent(FullCalendarData event) {
        this.data.add(event);
    }

}

我们可以检索事件列表,将其转换为 JSON 格式并调用此脚本:

@Override
public void start(Stage primaryStage) {
    Button btn=new Button("Add Events");
    btn.setOnAction(e->{

        // list of random events
        FullCalendarData data1=new FullCalendarData();
        data1.setEventName("Event 1");
        data1.setStartTime("2015-01-11T16:00:00");
        data1.setEndTime("2015-01-11T18:00:00");

        FullCalendarData data2=new FullCalendarData();
        data2.setEventName("Event 2");
        data2.setStartTime("2015-01-12T15:00:00");
        data2.setEndTime("2015-01-12T18:00:00");

        FullCalendarData data3=new FullCalendarData();
        data3.setEventName("Event 3");
        data3.setStartTime("2015-01-13T15:00:00");
        data3.setEndTime("2015-01-1316:00:00");

        CalendarEvents cal = new CalendarEvents();
        cal.addEvent(data1);
        cal.addEvent(data2);
        cal.addEvent(data3);

        Gson gson=new Gson();
        String json=gson.toJson(cal,CalendarEvents.class);

        engine.executeScript("addListEvents("+json+");");
    });

    createCalendar();

    Scene scene = new Scene(new VBox(webView,btn), 600, 400);

    primaryStage.setScene(scene);
    primaryStage.show();
}

您将在日历上安排您的活动: