简体   繁体   English

在MVC模型中以JSON格式显示查询结果

[英]Show Result of Query in JSON format in MVC Model

I wanna fetch some data from a database and show them in JSON format. 我想从数据库中获取一些数据并以JSON格式显示它们。 Im using MVC model. 我使用MVC模型。 I don't know how to do that. 我不知道该怎么做。

This is my DAO: 这是我的DAO:

public static List<NewsModel> getAll() {

        Connection con = ConnectionManagment.CreateConnection();
        List<NewsModel> newsList = new ArrayList<>();

        try {

            java.sql.PreparedStatement ps = con
                    .prepareStatement("select j.title, 
               j.content, j.displayDate from JournalArticle  j LIMIT 5");

            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                NewsModel news = new NewsModel();
                news.setTitle(rs.getString("title"));
                String date = rs.getString("displayDate");
                SimpleDateFormat smpl = new 
                               SimpleDateFormat("yyyy-MM-dd");
                news.setDisplayDate(smpl.parse(date));
                news.setContent(rs.getString("content"));

                newsList.add(news);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return newsList;
}

This is my servlet : 这是我的servlet:

List<NewsModel> news = (List<NewsModel>) new NewsModel();
news = SaipaDAO.getAll();

JSONArray newsArr = new JSONArray();
for (Object n : news) {
    JSONObject newsObj = new JSONObject();
}

Simple choice is to use Gson library. 简单的选择是使用Gson库。

Then: 然后:

NewsModel obj = new NewsModel ();
Gson gson = new Gson();
String json = gson.toJson(obj); //convert 
System.out.println(json);

This question is interesting too. 这个问题也很有趣。 Check it if you want. 如果需要,请检查它。

I found it. 我找到了。 I made a mistake in define foreach statment. 我在定义foreach语句时犯了一个错误。 this code works : 这段代码有效:

    List<NewsModel> news = new ArrayList<NewsModel>();
    JSONArray newsArr = new JSONArray();
    news = SaipaDAO.getAll();

    for (NewsModel n : news) {
        JSONObject newsObj = new JSONObject();

        newsObj.put("title", n.getTitle());
        newsObj.put("content", n.getContent());
        newsObj.put("displayDate", n.getDisplayDate());
        newsArr.add(newsObj);

    }

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

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