1. Datos en formato 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
}]
}
Nota: Los datos entrantes en formato json al fondo deben estar codificados encodeURIComponent (json)
function dlJson(){
dLong.layeropen(w-50, h-50, "字段校验", "${ctx}/Tbz4FieldInfoEntityController/fieldJson?data="+encodeURIComponent(json)+"&type=fieldcheckdlJson");
}
2 , dbtojson
Lea los datos de la base de datos y conviértalos en un archivo json, el
código central:
FileUtils.writeStringToFile(new File(ApplicationHome.getApplicationConfig()+"/fieldjson/"+filename),json.toString(), "UTF-8");
Donde
ApplicationHome.getApplicationConfig () + "/ fieldjson /" + filename
es la ubicación y el nombre de archivo del archivo que se almacenará
Nota: si no presta atención a UTF-8 , es fácil cometer errores, así que copie y pegue
Pasos de pensamiento de dbtojson:
1. Consultar los datos deseados de los datos
2. Convertir los datos en una cadena json
3. Leer la cadena json y escribirla en un archivo
Método 1: Utilice la conversión Map <String, Object> aquí
引入文件:
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, "操作失败。");
}
}
Atributos de SerializerFeature:
Para obtener más detalles, consulte la explicación detallada del serializador fastjson
Método 2: use la conversión de tableEntity de clase de entidad aquí
引入文件:
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
Pasos de pensamiento de jsontodb:
1. Determine si hay un archivo de datos en formato de cadena json. Si no existe, generará uno por defecto.
2. Lea el archivo de datos en formato de cadena json.
3. Conviértalo a la clase de entidad especificada.
4. Guarde los datos en la base de datos.
Nota : La cadena json debe tener el formato [{}], no se puede analizar sin []
Método 1:
引入文件:
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, "操作失败。");
}
}
Método 2:
引入文件:
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;
}
}
** consejos: Úselo al guardar datos en lotes
commonApiDao.batchInsert (lista);
mayor eficiencia
List<tableEntity> list =new LinkedList<>();
commonApiDao.batchInsert(list);
4. Conocimientos relacionados:
1. Anotación
@Data: Anotación en la clase; proporciona los métodos de obtención y configuración de todas las propiedades de la clase, y también proporciona métodos equals, canEqual, hashCode y toString
@Setter: anota en la propiedad; proporciona un método de configuración para la propiedad
@Getter: anota en el atributo; proporciona un método de obtención para el atributo
@ Log4j: anota en la clase; proporciona un objeto de registro log4j con un atributo llamado log para la clase
2. ¿Cómo puede una clase en Java llamar a un método en otra clase?
la clase java tiene dos métodos
Uno es el método de clase, que se modifica con static,
Uno es el método de instancia, que es el método sin modificación estática.
Los métodos de clase se pueden llamar al mismo tiempo que [nombre de clase. Nombre de método].
El método de instancia debe ser una instancia de [nueva clase a] primero, y luego llamado mediante [instancia. Nombre del método]. P.ej:
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("这是一个实例方法。");
}
}