简体   繁体   English

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

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

I am trying to get JSON data from a rest service. 我正在尝试从Rest服务获取JSON数据。 I know this is pretty simple for a GET service where you only have to provide the URI and Jasper studio can pull the data but I want to do this for a post rest service that also consumes some JSON input. 我知道这对于GET服务非常简单,您只需提供URI,Jasper studio即可提取数据,但我想为还需要一些JSON输入的post rest服务执行此操作。

Workflow will be something like: 工作流程将类似于:

  1. Send userID in request header and some JSON parameters in request body. 在请求标头中发送userID并在请求正文中发送一些JSON参数。
  2. Get JSON data as output. 获取JSON数据作为输出。
  3. Use JSON data to build report. 使用JSON数据生成报告。

I am new to Jasper and am using Jasper server 6 with Japser Studio 6 but I can't find any documentation to do something like this. 我是Jasper的新手,并且正在Japser Studio 6中使用Jasper服务器6,但是我找不到任何文档来做这样的事情。

I would appreciate if anyone can point me in the right direction regarding this. 如果有人能指出正确的方向,我将不胜感激。

The closes thing I can find is this link . 我能找到的关闭的东西就是这个链接 From there I get that I can create a constructor which will get the data from rest service but how do I serve it to the report? 从那里我可以创建一个构造函数,该构造函数将从rest服务获取数据,但是如何将其提供给报表? Also please note that the JSON object being retrieved here is a bit complex and will have at least 2 lists with any number of items. 还请注意,此处要检索的JSON对象有点复杂,并且将至少具有2个包含任意数量项的列表。

EDIT: 编辑:

Alright so my custom adapter is like this: 好了,所以我的自定义适配器是这样的:

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();
}

}

I am able to create an adapter and the Test Connection feature in Jasper Studio also returns true but I cant get it to read any of the fields in the JSON and auto-generate the report. 我能够创建适配器,Jasper Studio中的“测试连接”功能也返回true,但是我无法读取JSON中的任何字段并自动生成报告。 I only get a blank document. 我只得到一个空白文件。 FYI the JSON is something like: 仅供参考,JSON类似于:

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

Well, I feel stupid now but the solution was pretty easy. 好吧,我现在觉得很蠢,但是解决方案很简单。 Turns out you cant just return a JSON object. 原来你不能只返回一个JSON对象。 You need to return the fields and manually add the fields in the report. 您需要返回字段并在报告中手动添加字段。

For record purposes my final code look like this: 出于记录目的,我的最终代码如下所示:

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.

相关问题 当我尝试使用JSON数据时,POST到Jersey REST服务获取错误415不支持的媒体类型 - POST to Jersey REST service getting error 415 Unsupported Media Type when I try to consume JSON data 数据未显示在 jasper 报告中,但显示了元数据 - Data is not getting displayed in jasper reports but metadata is getting displayed 在Jasper报告中从哈希图中的对象映射获取值 - Getting values from object map inside a hash map in jasper reports 从查询中获取值,该查询在jasper报告中检索两个实体 - Getting values from a query that retrieves two entites in jasper reports 将带有JSON数据的POST请求从HTML发送到Java Rest Web服务时出现HTTP错误415 - HTTP Error 415 when sending POST request with JSON data from HTML to Java Rest web service 如何使带有JSON数据的post ajax调用到Jersey休息服务? - How to make post ajax call with JSON data to Jersey rest service? Jasper动态报告-使用jasper报告生成错误报告 - Jasper Dynamic Reports - using jasper reports to generate a report getting errors jasper 报告从 jasper 加载报告 - jasper reports loading report from jasper jasper报告子报告不起作用(不显示数据库中的数据) - jasper reports Subreport not working (not displaying data from database) Java的。 REST服务+ Jasper报告。 无法打印标签(或找不到) - Java. REST service + Jasper reports. Cannot print label (or cannot find)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM