Java读取json文件 和 csv文件

 
 
 

写在前面   CSDN没有保存   这是第二次写了。。某些内容已缺失

文件      Java(Map List)      持久层

 

 

读Json文件例子

案例一

像这种有集合有数组的json文件  压缩后扔给后台

使用  DealFileVO类

    private ConfsetVO confSet;
    private RecordSetUploadVO recordSet;
    private List temps;
    private List hums;
    private String username;

 

前台上传的是   

MultipartFile file  这种格式文件

下面的是把 MultipartFile转化为File   取出实体类

File f = null;
        try {
            f=File.createTempFile("tmp", null); // 创建file临时文件
            file.transferTo(f);
            //f.deleteOnExit(); // 将CommonsMultipartFile的临时文件的数据转到File 对象的临时文件
        } catch (IOException e) {
            e.printStackTrace();
        }

        DealFileVO result = readStream(f); //取出数据到实体类

        try {
            //insert   Label_data
            labelDataSaveService.insertData(result);

你可以添加一下检查文件内容正确性 (检查json文件里的数据重复性)

Gson 解析文件流  DealFileVO 实体类接收它

import org.apache.commons.io.FileUtils;
public static DealFileVO readStream(File file) {
        //File file = new File("D:\\data.txt");
        String content= null;
        try {
            content = FileUtils.readFileToString(file,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        Gson gson = new GsonBuilder().create();
        DealFileVO result = gson.fromJson(content, DealFileVO.class);
        return result;

    }

剩下的就是   保存到数据库

@Override
    public void insertData(DealFileVO result) {
        Ldata ldata = new Ldata();
        ldata.setConfid(result.getConfSet().getConfId());

        List tems = result.getTemps();
        List hums = result.getHums();
        int temsize = tems.size();
        for (int i = 0; i < temsize; i++) {
            ldata.setTemp( Float.parseFloat(tems.get(i).toString()));
            ldata.setHum( Float.parseFloat(hums.get(i).toString()));
            ldata.setCollectionTime(DateTimeUtil.LongToDate(result.getRecordSet().getStartDate()));
            dataMapper.insert(ldata);
        }
    }

 

 

 

 

 

 

案例二

这是百度地图的搜索周边的接口  ,我想调用这个接口,根据参数经纬度获取国家名字(参数为&location=纬度,经度)

http://api.map.baidu.com/geocoder/v2/?ak=D4bef01281a3d8dcea3f4db5cda88522&location=51.300000,0.100000&output=json&pois=1&roads=1

#这是百度地图搜索周边的文档
http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding-abroad

获取的json为:           

{
"status": 0,
"result": {
"location": {
"lng": 0.09999999999988274,
"lat": 51.29999922505652
},
"formatted_address": "Brasted Lane, Kent, England",
"business": "",
"addressComponent": {
"country": "England",
"country_code": 51441,
"country_code_iso": "GBR",
"country_code_iso2": "GB",
"province": "Kent",
"city": "Kent",
"city_level": 1,
"district": "",
"town": "",
"town_code": "",
"adcode": "0",
"street": "Brasted Lane",
"street_number": "",
"direction": "",
"distance": ""
},
"pois": [],
"roads": [],
"poiRegions": [],
"sematic_description": "",
"cityCode": 51488
}
}

country在result集合下 addressComponent集合里面,采用  org.json.JSONObject;

//发送 GET 请求
        String str1=sendGet("http://api.map.baidu.com/geocoder/v2/", "ak=D4bef01281a3d8dcea3f4db5cda88522&location=51.300000,0.100000&output=json&pois=radio[0].value&roads=1");
        //System.out.println(str1);
        JSONObject getjson = new JSONObject(str1);                //创建json对象(Json数据)
        //找到country  字符串遍历  剪切country后三位到下一个"结束  "country":"England"
        JSONObject getarray = getjson.getJSONObject("result");
        JSONObject addressComponent = getarray.getJSONObject("addressComponent");
        String country= addressComponent.get("country").toString();
        System.out.println(country);

 

 

 

 

案例三

{
  "name": "ALemon",
  "age": 24.2,
  "car": null,
  "major":["敲代码","学习"],
  "Nativeplace": {
  "city": "广州",
  "country": "China"
  }
}



import org.apache.commons.io.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;

public class Demo {
    public static void main(String args[]) throws IOException {

        File file=new File("mejson");
        String content= FileUtils.readFileToString(file,"UTF-8");
        JSONObject jsonObject=new JSONObject(content);
        System.out.println("姓名是:"+jsonObject.getString("name"));
        System.out.println("年龄:"+jsonObject.getDouble("age"));
        System.out.println("学到的技能:"+jsonObject.getJSONArray("major"));
        System.out.println("国家:"+jsonObject.getJSONObject("Nativeplace").getString("country"));

    }
}

原文链接:https://blog.csdn.net/ALemon_Y/article/details/71436194

https://github.com/aiLvXuan/ReadCsvFileDemo读取本地 和风天气的 中国地区城市 CSV 文件,并转换Json写入文件

 

读取csv  

 

--2020-07-30   突然发现这个 hutool工具挺好用的   https://hutool.cn/docs/index.html#/core/%E6%96%87%E6%9C%AC%E6%93%8D%E4%BD%9C/CSV%E6%96%87%E4%BB%B6%E5%A4%84%E7%90%86%E5%B7%A5%E5%85%B7-CsvUtil

 

也就是csv文件

。。。快下班了   以后来

突然觉得这种需求很傻比, 读取文件需要按照一定规则,这要求用户上传的csv文件格式必须按照我方规则,你管得了用户吗?

规则要求表格第一行是标题  所以在第二行开始读,然而 用户的没有标题。。

下面是我方规则

用户方

<dependency>
     <groupId>net.sourceforge.javacsv</groupId>
     <artifactId>javacsv</artifactId>
     <version>2.0</version>
</dependency>

 

public static List<String[]> readCSVFile(String csvFilePath) throws IOException {
        List<String[]> csvList = new ArrayList<String[]>();
        CsvReader reader = null;
        try {
            reader = new CsvReader(csvFilePath, ',', Charset.forName("UTF-8"));
            reader.readHeaders(); // 跳过表头   如果需要表头的话,不要写这句。
            while (reader.readRecord()) { // 逐行读入除表头的数据
                csvList.add(reader.getValues());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }


        return csvList;
    }

上面的逐行读取应该为逐列读取(去除第一列的第一行)
所以方法应该是先逐行读取   然后遍历   取每行的相应列加到List里  
public class Code {
    private Integer id;
    private String purpose;
    private String code;
    private String phone;
    private Date createTime;
    private Date expires;
    private Integer passtimes;
}
建一个javabean的类  内容就是csv一行对应的值    
while (reader.readRecord()) {   这里List<Code> 读取每一行时  把每一行保存到Code 类
再建一个类保存最终需要的逐列读取的List

@Getter
@Setter
public class CodeList {
        private List<Integer> id;
        private List<String> purpose;
        private List<String> code;
        private List<String> phone;
        private List<Date> createTime;
        private List<Date> expires;
        private List<Integer> passtimes;
}

CodeList result  = new CodeList();
for (Code code:list) {//list保存表格的所有行 code
     result.setCode(code.getCode());
     result.setPurpose(code.getPurpose());
                    .
                    .
                    .
                    
     }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

huang_ftpjh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值