首页 技术 正文
技术 2022年11月21日
0 收藏 521 点赞 4,155 浏览 1888 个字

读取json文件并转换为字符串

    /**
* 通过本地文件访问json并读取
*
* @param path:json文件路径
* @return:json文件的内容
*/
public static String ReadFile(String path) {
StringBuffer laststr = new StringBuffer();
File file = new File(path);// 打开文件
BufferedReader reader = null;
try {
FileInputStream in = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));// 读取文件
String tempString = null;
while ((tempString = reader.readLine()) != null) {
laststr = laststr.append(tempString);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException el) {
}
}
}
return laststr.toString();
}

解析json(fastjson)

public static void main(String args[]) {
String filePath = "D:/data.json";
String jsonString = ReadFile(filePath);
JSONArray jsonArr = JSON.parseArray(jsonString);
Map<String, Object> resultMap = new HashMap<String, Object>();
for (int i = 0; i < jsonArr.size(); i++) { Map data_map = (Map) jsonArr.get(i);//本次循环获取数据
Integer customer_id = (Integer) data_map.get("customer_id");
String customer_email = (String) data_map.get("customer_email");
String customer_firstname = (String) data_map.get("customer_firstname");
String customer_lastname = (String) data_map.get("customer_lastname"); String sku = (String) data_map.get("sku");
String created_at = (String) data_map.get("created_at"); Map level_1_map = (Map) resultMap.get(customer_id.toString());
if (null == level_1_map || level_1_map.size() <= 0) {
level_1_map = new HashMap<String, Object>();
level_1_map.put("customer_id", customer_id);
level_1_map.put("customer_email", customer_email);
level_1_map.put("customer_firstname", customer_firstname);
level_1_map.put("customer_lastname", customer_lastname);
} List list = level_1_map.get("list") == null ? new ArrayList<T>() : (List) level_1_map.get("list");
Map listMap = new HashMap<String, Object>();
listMap.put("sku", sku);
listMap.put("created_at", created_at);
list.add(listMap);
level_1_map.put("list", list); resultMap.put(customer_id.toString(), level_1_map);
}
System.out.println(JSON.toJSONString(resultMap)); }
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,078
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,553
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,402
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,177
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,814
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898