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

本文介绍了一种利用GSON库生成JSON数据的方法,并通过一个简单的示例展示了如何将一个字符串列表转换为JSON格式。此外,还展示了如何在网页中使用这些JSON数据进行图表展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值