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文件如下:

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

猜你喜欢

转载自www.linuxidc.com/Linux/2017-12/149351.htm