Jackson将json string转为Object,org.json读取json数组
从json文件读取json string或者自定义json string,将其转为object。下面采用的object为map,根据map读取json的某个数据,可以读取第一级的数据name,后来发现想转成JsonArray读取”red“时没撤了,只好用了其他方法。
最后用org.json包解决了(readJsonArray函数),有空再看看有没有更好的办法。
JSON文件如下:
1 { 2 "name":"name", 3 "id":"id", 4 "color":[ 5 {"red":"red","blue":"blue"}, 6 {"white":"white"} 7 ] 8 }
代码如下:
1 package com; 2 3 import 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; 8 9 import java.io.*; 10 import java.util.Map; 11 12 /** 13 * Hello world! 14 * 15 */ 16 public class JsonAnalysis 17 { 18 private static final Logger LOG = LoggerFactory.getLogger(JsonAnalysis.class); 19 public static void 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); 23 //Json字符串转java对象,比如转为Map对象读取其中数据 24 Map map = null; 25 Map mapFile = null; 26 try { 27 map = readValue(jsonString, Map.class); 28 mapFile = readValue(fileString, Map.class); 29 } catch (Exception e) { 30 e.printStackTrace(); 31 LOG.error("ReadValue occur exception when switch json string 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")); 39 40 try { 41 readJsonArray(fileString); 42 } catch (Exception e) { 43 e.printStackTrace(); 44 } 45 } 46 //Json string to object 47 private static <T> T readValue(String jsonStr, Class<T> valueType) throws Exception{ 48 ObjectMapper objectMapper = new ObjectMapper(); 49 try { 50 // Object object = objectMapper.readValue(jsonStr,Object.class); 51 return objectMapper.readValue(jsonStr,valueType); 52 } catch (IOException e) { 53 e.printStackTrace(); 54 } 55 return null; 56 } 57 //Read file and to string 58 private static 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); 70 return null; 71 } 72 } 73 //根据json string 获取json array,读取数据( 注意该部分引用的是org.json 包) 74 private static void 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 }