javaweb如何返回一个无键JSON数组给前端,以JSF为例

1、引入GSON2.4jar包

2、CreatJSONMB.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package JSONMB;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.ArrayList;

/**
 *
 * @author Administrator
 */
@Named(value = "creatJSON")
@SessionScoped
public class CreatJSONMB implements Serializable {

    Gson gson = new Gson();
    /**
     * Creates a new instance of CreatJSON
     */
    public CreatJSONMB() {
    }

    public String getJson() {
        
        ArrayList<String> books = new ArrayList<String>();  
        books.add("数学");  
        books.add("语文");  
        books.add("英语");  
        books.add("物理");  
        books.add("化学");  
        books.add("生物"); 
        return gson.toJson(books).toString();
    }

}

3、index.html

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Facelet Title</title>
        <script src="js/echarts.js" type="text/javascript"></script>
        <script src="js/jquery-3.1.1.min.js" type="text/javascript"></script>
        <script src="js/echarts-graph-modularity.min.js"></script>
        <link href="css/charts.css" rel="stylesheet" type="text/css"/>
    </h:head>
    <h:body>
        <!-- 为ECharts准备一个具备大小(宽高)的Dom -->
        <div id="main" style="width: 600px;height:400px;"></div>
        <script type="text/javascript">
            // 基于准备好的dom,初始化echarts实例
            var myChart = echarts.init(document.getElementById('main'));

            // 指定图表的配置项和数据
            var option = {
                title: {
                    text: 'ECharts 入门示例'
                },
                tooltip: {},
                legend: {
                    data: ['销量']
                },
                xAxis: {
                    data: #{creatJSON.json}
                },
                yAxis: {},
                series: [{
                        name: '销量',
                        type: 'bar',
                        data: [5, 20, 36, 10, 10, 20]
                    }]
            };

            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
        </script>
    </h:body>
</html>



猜你喜欢

转载自blog.csdn.net/qq_28562411/article/details/78759853