SpringBoot/Java 将MongoDB中的数据转换为json文件

本文介绍如何在SpringBoot项目中,利用MongoDB数据库存储的数据,转换成符合layui数据表格组件要求的json文件。通过创建实体类、引入fastjson库,并在测试类中实现数据转换操作。
摘要由CSDN通过智能技术生成

项目背景:
我最近在做SpringBoot的项目,其中数据库使用的是MongoDB,前端框架用的是layui。在我使用layui的数据表格组件时,其数据接口对应的是json文件,所有我得将MongoDB中的collection转换为json文件。

MongoDB在SpringBoot中的具体配置在这里就不具体赘述了,直接进入正题

如下是存储在MongoDB中的数据,存在了paper_Info集合中。
在这里插入图片描述
建立一个实体类,对应这这个集合的名字。
类的属性要对应着collection中的索引,在写完类的属性后,alt+insert健idea自动补全getter和setter方法。

package com.hhu.bigdatasys.rtenzyme.entity;

import lombok.Data;
import lombok.ToString;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.List;

@Data
@ToString
@Document(collection = "paper_info") //对应着MongoDB中的collection名称
public class paper_info {
   

    private String _id;

    public String get_id() {
   
        return _id;
    }

    public void set_id(String _id) {
   
        this._id = _id;
    }

    //论文所属的老师
    private String index;

    //论文的标题
    private String title;

    //作者列表
    private List<String> authors;

    //论文来源
    private String source;


    public String getIndex() {
   
        return index;
    }

    public void setIndex(String index) {
   
        this.index = index;
    }

    public String getTitle() {
   
        return title;
    }

    public void setTitle(String title) {
   
        this.title = title;
    }

    public List<String> getAuthors() {
   
        return authors;
    }

    public void setAuthors(List<String> authors) {
   
        this.authors = authors;
    }

    public String getSource() {
   
        return source;
    }

    public void setSource(String source) {
   
        this.source = source;
    }

    public String getTimes() {
   
        return times;
    }

    public void setTimes(String times) {
   
        this.times = times;
    }

    public String getDatabase() {
   
        return database;
    }

    public void setDatabase(String database) {
   
        this.database = database;
    }


    //论文发表的时间
    private String times;

    //期刊类型

    private String database;

    //引用次数
    private int counted;

    public int getCounted() {
   
        return counted;
    }

    public void setCounted(int counted) {
   
        this.counted = counted;
    }


}

接下来先要载入fastjson的maven reporsity。在pom.xml中的dependency下加入:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.72</version>
        </dependency>

layui数据表格的异步数据的结构要求如下:

{
   
  "code": 0,
  "msg": "",
  "count": 1000,
  "data": [{
   }, {
   }]
} 

其中code值为0代表着成功获取数据,count是data数据条的个数,msg是提示文本。

为了方便我们可以在Test文件中写相应的操作。

@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoTest {
   

    final static private Logger logger = LoggerFactory.getLogger(MongoTest.class);

    @Resource
    MongoTemplate mongoTemplate;

    @Test
    public void testfind() throws IOException {
   
        Query qury = new Query();
        List<paper_info> paperInfoList;
        //该查询方式可以查到mongoDB中一个collection中所有的数据,返回paper_info类型的数据对象
        paperInfoList = mongoTemplate.find(new Query(new Criteria()),paper_info.class);
        //将bean类型的数据对象转化为json字符串,测试使用
        String jsonString = JSON.toJSONString(paperInfoList.get(0));
        System.out.println("Test:"+jsonString);
        //构建json对象的列表
        List<JSONObject> jsonObjectList = new ArrayList<>();
        for(paper_info item:paperInfoList){
    //构建迭代器
            try {
   
                String jsonStr = JSON.toJSONString(item);//将paper_info对象转换为json字符串
                JSONObject jsonObject = (JSONObject) JSON.parse(jsonStr);//再将字符串转换为json对象
                jsonObjectList.add(jsonObject);//加入到jsonObject列表中
            } catch (Exception e) {
   
                e.printStackTrace();
            }

        }
        JSONObject jsonContainer = new JSONObject();//构建json容器
        //根据layui数据表格的数据接口的要求构建json结构
        jsonContainer.put("msg","");
        jsonContainer.put("count",paperInfoList.size());
        jsonContainer.put("code",0);
        jsonContainer.put("data",jsonObjectList);
        System.out.println(jsonContainer);
        //将json写入到文件中
        File file = new File("src\\main\\resources\\static\\paper_info.json");
        FileWriter fileWritter = new FileWriter(file,false);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWritter);
        bufferedWriter.write(jsonContainer.toJSONString());
        bufferedWriter.close();
    }
}

结果展示

{
   "msg":"","code":0,"data":[{
   "database":"期刊","times":"2020-06-20","counted":0,"index":"许峰","_id":"5f0bcabbd8a3be14440e7783","source":"湖北民族大学学报(医学版)","title":"纳布啡联合丙泊酚用于无痛人工流产术的效果观察","authors":["许峰","樊志龙"]},{
   "database":"期刊","times"
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 获取 MongoDB 的 GridFSBucket 数据,可以通过使用 Spring Data MongoDB 提供的 GridFsTemplate 类来实现。 首先,确保你的 Spring Boot 项目已经添加了 Spring Data MongoDB 的依赖。然后,创建一个 GridFsTemplate 的实例,并注入 MongoDB 的 MongoDatabase 对象。 ```java import com.mongodb.client.gridfs.GridFSBucket; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.stereotype.Component; @Component public class GridFSExample { private final GridFsTemplate gridFsTemplate; private final GridFSBucket gridFSBucket; @Autowired public GridFSExample(MongoDbFactory mongoDbFactory, GridFsTemplate gridFsTemplate) { this.gridFsTemplate = gridFsTemplate; this.gridFSBucket = GridFSBuckets.create(mongoDbFactory.getDb()); } // 在这里可以编写其他方法来获取 GridFSBucket 数据 } ``` 现在,你可以在 `GridFSExample` 类编写其他方法来获取 GridFSBucket 数据。例如,你可以使用 `gridFsTemplate` 对象来获取文件的元数据信息: ```java import com.mongodb.client.gridfs.model.GridFSFile; import org.springframework.stereotype.Component; @Component public class GridFSExample { // ... public GridFSFile getFileMetaData(String fileId) { return gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId))); } // ... } ``` 你还可以使用 `gridFSBucket` 对象来获取文件的输入流,以及执行其他操作: ```java import org.bson.types.ObjectId; import org.springframework.stereotype.Component; import java.io.InputStream; @Component public class GridFSExample { // ... public InputStream getFileInputStream(ObjectId fileId) { return gridFSBucket.openDownloadStream(fileId); } // ... } ``` 这样,你就可以在 Spring Boot 通过 GridFsTemplate 和 GridFSBucket 来获取 MongoDB 的 GridFSBucket 数据了。记得在使用前配置好 MongoDB 的连接信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值