如何打印 json 格式以使用 bean 进行控制台

how to print json format to console using bean

我正在通过 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 应该如何打印到控制台?

请仔细阅读堆栈跟踪。您的问题与打印到控制台无关。你离那里不近。

再看一遍那个错误:

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> 默认为 JSON 创建一个 string 表示。您可能做了其他未在问题中显示的事情...

更新

要解决您眼前的问题,您只需要 print() 像这样:

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

然而,根据您的 List<Posts>,完全不清楚为什么要将 <int-jdbc:inbound-channel-adapter>List<Posts> 结果转换为 JSON,因为 he/she 不会预计 JSON 下游。