在JSTL页面上的表上获取JSON数据

时间:2019-03-14 00:47:48

标签: java json api servlets jstl

所以我正在使用amiibo api提取数据,并显示表中返回的内容。现在,我只是将该系列放在桌子上,以确保它可以正常工作,但不能成功!

这是我的桌子:

<table class="table table-striped table-hover table-sm">
            <thead>
                <tr>
                    <th class="col-sm-1" scope="col">#</th>
                    <th class="col-sm-11" scope="col">Amiibo</th>
                </tr>
            </thead>
            <c:forEach var="amiibo" items="${amiibos}" varStatus="status">
                <tr>
                    <th scope="row">${status.count}</th>
                    <td>${amiibo.amiiboSeries}</td>
                </tr>
            </c:forEach> 
        </table>

这是我的servlet,它提取api数据并将其放入列表:

String json = callAmiiboApi(input.getAmiibo());

        // Check for valid json format.  If false, String contains an error message.
        if (json.startsWith("{") || json.startsWith("[")) {
            Gson gson = new Gson();
            ArrayList<Amiibo> amiibos = gson.fromJson(json, new TypeToken<ArrayList<Amiibo>>(){}.getType());

            //get list of elements 
            if (!amiibos.isEmpty() && amiibos.size() > 0) {
                request.setAttribute("amiibos", amiibos);
            }  
        }

这是我的对象:

public class Amiibo implements Serializable
{
    public String amiiboSeries;
    public String character;
    public String gameSeries;
    public String head;
    public String image;
    public String name;
    public String[] release;
    public String tail;
    public String type;

    public Amiibo()
    {
        amiiboSeries = "";
        character = "";
        gameSeries = "";
        head = "";
        image = "";
        name = "";
        release = new String[0];
        tail = "";
        type = "";
    }

    public String getAmiiboSeries()
    {
        return amiiboSeries;
    }

这是我得到的错误:

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

有人知道我在提取此数据时做错了什么吗?我认为该api可以很好地访问,我认为我的问题在于如何显示它(可能是在将其放入列表时?)。

-编辑-

这是我获取用户输入的输入类

import java.io.Serializable;

public class Input implements Serializable {
    private String amiibo;

    public Input() {
        this("");
    }

    public Input(String amiibo) {
        this.amiibo = amiibo;
    }

    public String getAmiibo() {
        return amiibo;
    }

    public void setAmiibo(String amiibo) {
        this.amiibo = amiibo;
    }  
}

1 个答案:

答案 0 :(得分:1)

克里特包装对象:

class AmiiboResponse {

    private List<Amiibo> amiibo;

    public List<Amiibo> getAmiibo() {
        return amiibo;
    }

    public void setAmiibo(List<Amiibo> amiibo) {
        this.amiibo = amiibo;
    }
}

并以这种方式反序列化:

List<Amiibo> amiibos = gson.fromJson(json, AmiiboResponse.class).getAmiibo();