野猪大改造 1080p_Jackson将json string转为Object,org.json读取json数组
Jackson是常用的json解析工具之一巢湖乐虎资讯网--,具有json string转object(objectMapper.readValue),object转string,json string合法性判断等等功能。
从json文件读取json string或者自定义json string,将其转为object。下面采用的object为map,根据map读取json的某个数据,可以读取第一级的数据name,后来发现想转成JsonArray读取”red“时没撤了,只好用了其他方法。
最后用org.json包解决了(readJsonArray函数),有空再看看有没有更好的办法。org.json是Java常用的Json解析工具,主要提供JSONObject和JSONArray类。
JSON文件如下:
1 { 2 "name":"name", 3 "id":"id", 4 "color":[ 5 {"red":"red","blue":"blue"}, 6 {"white":"white"} 7 ] 8 }
代码如下:
1 package com; org.codehaus.jackson.map.ObjectMapper; 4 import org.json.JSONArray; 5 import org.json.JSONObject; 6 import org.slf4j.Logger; 7 import org.slf4j.LoggerFactory; java.io.*; 10 import java.util.Map; * Hello world! 14 * JsonAnalysis 17 { Logger LOG = LoggerFactory.getLogger(JsonAnalysis.class); main(String[] args) throws FileNotFoundException { 20 String jsonString = "{"address":"address","name":"name","id":"1","email":"email"}"; 21 FileReader fileReader = new FileReader("E:\JsonAnalysis\src\test.json"); 22 String fileString = readFile(fileReader); Map map = null; 25 Map mapFile = null; 26 try { 27 map = readValue河池乐虎资讯网--(jsonString, Map.class); 28 mapFile = re文昌乐虎资讯网--凉山乐虎资讯网--(fileString, Map.class); 29 } catch (Exception e) { 30 e.printStackTrace(); 31 LOG.error("ReadValue occur exception when switch json str曲靖乐虎资讯网-- to map"); 32 } 33 System.out.println(map != null ? map.get("id") : null); 34 if (mapFile==null){ 35 LOG.info("Json map form file is empty"); 36 return; 37 } 38 System.out.println(mapFile.get("name")); { 41 readJsonArray(fileString); 42 } catch (Exception e) { 43 e.printStackTrace(); 44 } 45 } <T> T readValue(String jsonStr, Class<T> valueType) throws Exception{ 48 ObjectMapper objectMapper = new ObjectMapper(); 49 try { objectMapper.readValue(jsonStr,valueType); 52 } catch (IOException e) { 53 e.printStackTrace(); 54 } ; 56 } String readFile(FileReader fileReader){ 59 BufferedReader bufferedReader = new BufferedReader(fileReader); 60 StringBuilder fileStr = new StringBuilder(); 61 try { 62 String eachLine石河子乐虎资讯网--; 63 while ((eachLine=bufferedReader.readLine())!=null){ 64 fileStr.append(eachLine); 65 } 66 return fileStr.toString(); 67 } catch (IOException e1) { 68 e1.printStackTrace(); 69 LOG.error("Occur exception when read file,file={}",fileReader); ; 71 } 72 } readJsonArray(String jsonStr) throws Exception { 75 JSONObject jsonObject = new JSONObject(jsonStr); 76 JSONArray jsonArray = jsonObject.getJSONArray("color"); 77 78 JSONObject jsonObject1 = jsonArray.getJSONObject(0); 79 System.out.println(jsonObject1.get("red")); 80 } 81 }
当前文章:
发布时间:2017-12-16 03:19:41
{索引池}