Java 将数据库表数据转换为json格式的文件 将json格式的文件存入数据库

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

1,json格式数据

{
	"createtime": "2021-01-09 15:38:31.322",
	"data": [{
		"idno": "121",
		"field_code": "MVR_5_1_2",
		"submitname": "MVR-5-1-2",
		"fllevel2showclass": " dl_118 dl_120",
		"xh": 0,
		"id": "055d6afd1006f66d5e8fb3a97501e75d",
		"fieldlink": "",
		"fllevel2xh": 0
	}, {
		"idno": "119",
		"field_code": "MVR_5_1_1",
		"submitname": "MVR-5-1-1",
		"fllevel2showclass": " dl_118",
		"xh": 0,
		"id": "05d3b2574ee78ab788afd094d4a47c84",
		"fieldlink": "{\"values\":[{\"hide\":\"\",\"show\":\"120\",\"rule\":\"==::y\",\"oper\":\"==\",\"type\":\"hide\",\"maxOper\":\"\",\"maxRule\":\"\"}],\"type\":\"hide\"}",
		"fllevel2xh": 0
	}]
}

注意:json格式传入数据到后台,需要进行编码 encodeURIComponent(json)

 function dlJson(){
    dLong.layeropen(w-50, h-50, "字段校验", "${ctx}/Tbz4FieldInfoEntityController/fieldJson?data="+encodeURIComponent(json)+"&type=fieldcheckdlJson");
 }

2,dbtojson

读取数据库的数据,并转为json文件,
在这里插入图片描述
核心代码:


 FileUtils.writeStringToFile(new File(ApplicationHome.getApplicationConfig()+"/fieldjson/"+filename),json.toString(), "UTF-8");
 

其中
ApplicationHome.getApplicationConfig()+"/fieldjson/"+filename
是文件要存放的位置以及文件名

注意:UTF-8 不注意的话很容易写错,最好复制粘贴

在这里插入图片描述

dbtojson思路步骤:

1,从数据里查询想要的数据
2,将数据转化为json字符串
3,读取json字符串并写入文件

法一:这里使用Map<String, Object>转换

 引入文件:
	 import net.sf.json.JSONObject;
	 import cn.hutool.json.JSONArray;
	 import cn.hutool.json.JSONUtil;
	 
     @RequestMapping("/tojson")
     @ResponseBody
     public Map tojson(@RequestParam HashMap<String,String> paraMap) {
        try {
            String sql = "select * from table";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            Map<String, Object> objectMap=new HashMap<>();
            objectMap.put("data", list);
            objectMap.put("createtime", new Timestamp(System.currentTimeMillis()).toString());
            JSONObject json = JSONObject.fromObject(objectMap);
            String filename=paraMap.get("bzcode")+".json";
            FileUtils.writeStringToFile(new File(ApplicationHome.getApplicationConfig()+"/fieldjson/"+filename)
                    ,json.toJSONString(objectMap,
                            SerializerFeature.PrettyFormat
                            ,SerializerFeature.SortField
                            ,SerializerFeature.WriteNullListAsEmpty
                            ,SerializerFeature.WriteMapNullValue
                            ,SerializerFeature.WriteNonStringKeyAsString
                    ), "UTF-8");//格式化文件数据
            HashMap<String, Object> result = createResult(true, "操作成功。");
            return result;
        } catch (Exception e) {
            log.error("系统错误!" + e.getMessage(), e);
            return createResult(Boolean.FALSE, "操作失败。");
        }
     }
	

SerializerFeature属性:在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

更多详情,请查阅 fastjson SerializerFeature详解

法二:这里使用实体类tableEntity转换

 引入文件:
	import com.alibaba.fastjson.JSON;

    @RequestMapping("/tojson")
    @ResponseBody
    public Map tojson(@RequestParam HashMap<String,String> paraMap) {
        try {
            String sql = "select * from table";
            List<tableEntity> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper(tableEntity.class));
            Map<String, Object> objectMap=new HashMap<>();
            objectMap.put("data", list);
            objectMap.put("createtime", new Timestamp(System.currentTimeMillis()).toString());
            String filename=paraMap.get("bzcode")+".json";
            FileUtils.writeStringToFile(new File(ApplicationHome.getApplicationConfig()+"/fieldjson/"+filename)
                    ,JSON.toJSONString(objectMap,true), "UTF-8");//一般处理,没有格式化文件数据
            HashMap<String, Object> result = createResult(true, "操作成功。");
            return result;
        } catch (Exception e) {
            log.error("系统错误!" + e.getMessage(), e);
            return createResult(Boolean.FALSE, "操作失败。");
        }
    }

3,jsontodb

jsontodb思路步骤:

1,判断是否存在这个json字符串格式数据的文件,如果不存在,默认生成一个
2,读取json字符串格式数据的文件
3,转换为指定的实体类
4,将数据保存进数据库中

注意:json字符串一定要 [{}] 这个格式,缺少 [] 是无法解析的

法一:


 引入文件:
	import cn.hutool.json.JSONArray;
	import cn.hutool.json.JSONUtil;
	import cn.hutool.json.JSONObject;


	//想要调用其他类的方法,使用注解
    @Autowired
    Tbz4FieldInfoEntityController tbz4FieldInfoEntityController;
    
     //复制,清空,导入  如果找不到文件,自动生成一个
    @RequestMapping("/jsontodb")
    @ResponseBody
    public Map jsontodb(@RequestParam HashMap<String,String> paraMap, Model model) {
        try {
            //如果找不到文件,自动生成一个
            String filename=paraMap.get("bzcode")+".json";
            if(!new File(ApplicationHome.getApplicationConfig()+"/fieldjson/"+filename).exists()){
                tbz4FieldInfoEntityController.tojson(paraMap);
            }

            /*String tablenew="table"+String.valueOf(System.currentTimeMillis());
            String sqlcy="select * into "+tablenew+" from table";
            jdbcTemplate.execute(sqlcy);
            String sqldel="delete from table where bid='"+paraMap.get("bid")+"'";
            jdbcTemplate.execute(sqldel);*/

            String data= FileUtils.readFileToString(new File(ApplicationHome.getApplicationConfig()+"/fieldjson/"+filename),"UTF-8");
            String json="["+data+"]";
            List<Tbz4FieldInfoEntity> list =new LinkedList<>();
            JSONArray picArray = new JSONArray(json);
            list = JSONUtil.toList(new JSONArray(((JSONObject) picArray.get(0)).get("data").toString()), Tbz4FieldInfoEntity.class);
            tbz4FieldInfoEntityDao.saveAll(list);

            HashMap<String, Object> result = createResult(true, "操作成功。");
            return result;
        } catch (Exception e) {
            log.error("系统错误!" + e.getMessage(), e);
            return createResult(Boolean.FALSE, "操作失败。");
        }
    }

法二:


 引入文件:
	import com.alibaba.fastjson.JSON;

	@RequestMapping("/jsontodb")
    @ResponseBody
    public Map jsontodb(@RequestParam HashMap<String,String> paraMap, Model model) {
        try {
            //如果找不到文件,自动生成一个
            String filename=paraMap.get("bzcode")+".json";
            if(!new File(ApplicationHome.getApplicationConfig()+"/fieldjson/"+filename).exists()){
                tbz4FieldInfoEntityController.tojson(paraMap);
            }

            /*String tablenew="table"+String.valueOf(System.currentTimeMillis());
            String sqlcy="select * into "+tablenew+" from table ";
            jdbcTemplate.execute(sqlcy);
            String sqldel="delete from table where bid='"+paraMap.get("bid")+"'";
            jdbcTemplate.execute(sqldel);*/

            String data= FileUtils.readFileToString(new File(ApplicationHome.getApplicationConfig()+"/fieldjson/"+filename),"UTF-8");
            List<tableEntity> list =new LinkedList<>();
            //Tbz4FieldInfoEntityController.FieldJson为类中静态类
            Tbz4FieldInfoEntityController.FieldJson fieldJson = JSON.parseObject(data, Tbz4FieldInfoEntityController.FieldJson.class);
            tbz4FieldInfoEntityDao.saveAll(fieldJson.data);
            HashMap<String, Object> result = createResult(true, "操作成功。");
            return result;
        } catch (Exception e) {
            log.error("系统错误!" + e.getMessage(), e);
            return createResult(Boolean.FALSE, "操作失败。");
        }
    }


	@Slf4j
	@Controller
	@RequestMapping(value = "/Tbz4FieldInfoEntityController")
	public class Tbz4FieldInfoEntityController extends BaseControllerZfpt {
	//字段命名一定要和json格式数据的标签一致
	//@Data:注解在类上;提供类所有属性的 getting 和 setting 方法,
		  @Data
		   public static class FieldJson{
		       String createtime;
		       List<tableEntity> data;
		   }
	}

**tips:批量保存数据的时候使用

commonApiDao.batchInsert(list);

效率更高

 List<tableEntity> list =new LinkedList<>();
 commonApiDao.batchInsert(list); 

4,相关知识:

1,注解

@Data:注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法

@Setter:注解在属性上;为属性提供 setting 方法

@Getter:注解在属性上;为属性提供 getting 方法

@Log4j :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象

2,Java中的一个类怎么调用另一个类中的方法?

java类有两种方法

一种是类方法,就是用static修饰的,

一种是实例方法,就是没有static修饰的方法。

类方法可以同时【类名.方法名】的方式调用。

而实例方法必须先【new一个类】的实例,然后通过【实例.方法名】的方式调用。例如:

	public class MethodCall
	{
	    public static void main(String[] args)
	    {
	        Test.sayStatic();
	        Test test = new Test();
	        test.sayInstance();
	    }
	}
	class Test
	{
	    public static void sayStatic()
	    {
	        System.out.println("这是一个静态方法。");
	    }
	    public void sayInstance()
	    {
	        System.out.println("这是一个实例方法。");
	    }
	}

在这里插入图片描述

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值