{
"name":"name",
"id":"id",
"color":[
{"red":"red","blue":"blue"},
{"white":"white"}
]
}
package com;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Map;
/**
* Hello world!
*
*/
public class JsonAnalysis
{
private static final Logger LOG = LoggerFactory.getLogger(JsonAnalysis.class);
public static void main(String[] args) throws FileNotFoundException {
String jsonString = "{\"address\":\"address\",\"name\":\"name\",\"id\":\"1\",\"email\":\"email\"}";
FileReader fileReader = new FileReader("E:\\JsonAnalysis\\src\\test.json");
String fileString = readFile(fileReader);
//Json字符串转java对象,比如转为Map对象读取其中数据
Map map = null;
Map mapFile = null;
try {
map = readValue(jsonString, Map.class);
mapFile = readValue(fileString, Map.class);
} catch (Exception e) {
e.printStackTrace();
LOG.error("ReadValue occur exception when switch json string to map");
}
System.out.println(map != null ? map.get("id") : null);
if (mapFile==null){
LOG.info("Json map form file is empty");
return;
}
System.out.println(mapFile.get("name"));
try {
readJsonArray(fileString);
} catch (Exception e) {
e.printStackTrace();
}
}
//Json string to object
private static <T> T readValue(String jsonStr, Class<T> valueType) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
try {
// Object object = objectMapper.readValue(jsonStr,Object.class);
return objectMapper.readValue(jsonStr,valueType);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Read file and to string
private static String readFile(FileReader fileReader){
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder fileStr = new StringBuilder();
try {
String eachLine;
while ((eachLine=bufferedReader.readLine())!=null){
fileStr.append(eachLine);
}
return fileStr.toString();
} catch (IOException e1) {
e1.printStackTrace();
LOG.error("Occur exception when read file,file={}",fileReader);
return null;
}
}
//根据json string 获取json array,读取数据( 注意该部分引用的是org.json 包)
private static void readJsonArray(String jsonStr) throws Exception {
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray = jsonObject.getJSONArray("color");
JSONObject jsonObject1 = jsonArray.getJSONObject(0);
System.out.println(jsonObject1.get("red"));
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有