java—如何使用bean将json格式打印到控制台

qgelzfjb  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(504)

我正在用spring集成将对象转换为json。

<int-jdbc:inbound-channel-adapter query="SELECT * FROM posts" row-mapper="postMapper"
                                      channel="dataInbound" data-source="dataSource">
        <int:poller fixed-rate="5000" />
    </int-jdbc:inbound-channel-adapter>

    <int:channel id="dataInbound" />

    <int:object-to-json-transformer input-channel="dataInbound" output-channel="printing"/>
    <int:service-activator id="printing" method="print"
                           input-channel="print" ref="eventActivator"/>
 <bean id="postMapper" class="com.example.domain.PostsMapper"/>

    <bean id="eventActivator" class="com.example.Dispatcher"/>
public class Posts {

    private String id;
    private String title;
    private String author;
   ...Constructor and setters/getters...
}

public class PostsMapper implements RowMapper<Posts> {

    public Posts mapRow(ResultSet rs, int rowNum) throws SQLException{
        String id = rs.getString("id");
        String title = rs.getString("title");
        String author = rs.getString("author");
        return new Posts(id, title, author);
    }
}

但如何将变压器打印到控制台 <int:service-activator> . 我试过了,但没用:

public void print(List<Posts> posts){
        for (Posts post: posts){
            System.out.print("\n*****" + post);
        }
    }

我遇到的错误:

Failed to convert from type [java.util.ArrayList<?>] to type [java.util.List<com.example.domain.Posts>] for value '[{id=1, title=test, author=me}]'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.util.LinkedHashMap<?, ?>] to type [com.example.domain.Posts]
No converter found capable of converting from type [java.util.LinkedHashMap<?, ?>] to type [com.example.domain.Posts]
Problem invoking method: public void com.example.Dispatcher.print(java.util.List)

我的朋友怎么样 bean 打印到控制台应该是什么样子?

acruukt9

acruukt91#

请仔细阅读堆叠痕迹。。您的问题与打印到控制台无关。你离这儿不近。
再看一遍那个错误:

No converter found capable of converting from type [java.util.LinkedHashMap<?, ?>] to type [com.example.domain.Posts]

所以,你的 payload 真的不是 List<Posts> 它是一个 ArrayList<LinkedHashMap<?, ?>> 最后。
不知道怎么回事。这个 <int:object-to-json-transformer> 创建 string 默认情况下表示json。你可能做了一些问题中没有表现出来的事情。。。
更新
为了解决眼前的问题,你只需要 print() 这样地:

public void print(List<Map<?, ?>> posts){

但是根据你的 List<Posts> ,这是完全不清楚为什么要转换的 List<Posts> 结果来自 <int-jdbc:inbound-channel-adapter> 对于json,因为他/她不期望json。

相关问题