Jackson将json string转为Object,org.json读取json数组的实例
程序员文章站
2024-02-22 11:59:10
从json文件读取json string或者自定义json string,将其转为object。下面采用的object为map,根据map读取json的某个数据,可以读取第...
从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数组的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。