繁体   English   中英

Jasper Reports:从发布后服务获取JSON数据

[英]Jasper Reports: getting JSON data from a post rest service

我正在尝试从Rest服务获取JSON数据。 我知道这对于GET服务非常简单,您只需提供URI,Jasper studio即可提取数据,但我想为还需要一些JSON输入的post rest服务执行此操作。

工作流程将类似于:

  1. 在请求标头中发送userID并在请求正文中发送一些JSON参数。
  2. 获取JSON数据作为输出。
  3. 使用JSON数据生成报告。

我是Jasper的新手,并且正在Japser Studio 6中使用Jasper服务器6,但是我找不到任何文档来做这样的事情。

如果有人能指出正确的方向,我将不胜感激。

我能找到的关闭的东西就是这个链接 从那里我可以创建一个构造函数,该构造函数将从rest服务获取数据,但是如何将其提供给报表? 还请注意,此处要检索的JSON对象有点复杂,并且将至少具有2个包含任意数量项的列表。

编辑:

好了,所以我的自定义适配器是这样的:

package CustomDataAdapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONObject;

public class SearchAdapter implements JRDataSource {
/**
 * This will hold the JSON returned by generic search service
 */
private JSONObject json = null;

/**
 * Will create the object with data retrieved from service.
 */
public SearchAdapter() {
    String url = "[URL is here]";
    String request = "{searchType: \"TEST\", searchTxt: \"TEST\"}";

    // Setting up post client and request.
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    HttpResponse response = null;

    post.setHeader("userId", "1000");
    post.setHeader("Content-Type", "application/json");

    // Setting up Request payload
    HttpEntity entity = null;
    try {
        entity = new StringEntity(request);
        post.setEntity(entity);

        // do post
        response = client.execute(post);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Reading Server Response
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new Exception("Search Failed");
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        String inputLine;
        StringBuffer resp = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            resp.append(inputLine);
        }

        in.close();

        this.json = new JSONObject(resp.toString());
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

/*
 * (non-Javadoc)
 * 
 * @see
 * net.sf.jasperreports.engine.JRDataSource#getFieldValue(net.sf.jasperreports
 * .engine.JRField)
 */
public Object getFieldValue(JRField field) throws JRException {
    // TODO Auto-generated method
    // stubhttp://community-static.jaspersoft.com/sites/default/files/images/0.png
    return this.json;
}

/*
 * (non-Javadoc)
 * 
 * @see net.sf.jasperreports.engine.JRDataSource#next()
 */
public boolean next() throws JRException {
    return (this.json != null);
}

/**
 * Return an instance of the class that implements the custom data adapter.
 */
public static JRDataSource getDataSource() {
    return new SearchAdapter();
}

}

我能够创建适配器,Jasper Studio中的“测试连接”功能也返回true,但是我无法读取JSON中的任何字段并自动生成报告。 我只得到一个空白文件。 仅供参考,JSON类似于:

{
"key": "value",
"key": "value",
"key": [list],
"key": [list]
}

好吧,我现在觉得很蠢,但是解决方案很简单。 原来你不能只返回一个JSON对象。 您需要返回字段并在报告中手动添加字段。

出于记录目的,我的最终代码如下所示:

package CustomDataAdapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONException;
import org.json.JSONObject;

public class SearchAdapter implements JRDataSource {

    /**
     * This will hold the JSON returned by generic search service
     */
    private JSONObject json = null;

    /**
     * Ensures that we infinitely calling the service.
     */
    private boolean flag = false;
    /**
     * Will create the object with data retrieved from service.
     */
    private void setJson() {
        String url = "[URL is here]";
        String request = "{\"searchType\": \"Test\", \"searchTxt\": \"Test\"}";

        // Setting up post client and request.
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        HttpResponse response = null;

        post.setHeader("userId", "1000");
        post.setHeader("Content-Type", "application/json");

        // Setting up Request payload
        StringEntity entity = null;
        try {
            entity = new StringEntity(request);
            post.setEntity(entity);

            // do post
            response = client.execute(post);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Reading Server Response
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                // Thrown Exception in case things go wrong
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent()));
                String inputLine;
                StringBuffer resp = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    resp.append(inputLine);
                }

                in.close();

                String ex = "Search Failed. Status Code: " + statusCode;
                ex += "\n Error: " + resp.toString();
                throw new Exception(ex);
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            String inputLine;
            StringBuffer resp = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                resp.append(inputLine);
            }

            in.close();

            this.json = new JSONObject(resp.toString());
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * net.sf.jasperreports.engine.JRDataSource#getFieldValue(net.sf.jasperreports
     * .engine.JRField)
     */
    @Override
    public Object getFieldValue(JRField field) throws JRException {
        // TODO Auto-generated method
        // stubhttp://community-static.jaspersoft.com/sites/default/files/images/0.png
        try {
            return this.json.get(field.getName());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see net.sf.jasperreports.engine.JRDataSource#next()
     */
    @Override
    public boolean next() throws JRException {
        if (this.json != null && !flag) {
            flag = true;
            return true;
        } else {
            return false;
        }
    }

    /**
     * Return an instance of the class that implements the custom data adapter.
     */
    public static JRDataSource getDataSource() {
        SearchAdapter adapter = new SearchAdapter();
        adapter.setJson();
        return adapter;
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM