从json文件读取json string或者自定义json string,将其转为object。下面采用的object为map,根据map读取json的某个数据,可以读取第一级的数据name,后来发现想转成JsonArray读取”red“时没撤了,只好用了其他方法。

最后用org.json包解决了(readJsonArray函数),有空再看看有没有更好的办法。

JSON文件如下:

{
 "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"));
 }
}

以上这篇Jackson将json string转为Object,org.json读取json数组的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

02-06 14:24