Jackson将json string转为Object,org.json读取json数组的实例
从json文件读取jsonstring或者自定义jsonstring,将其转为object。下面采用的object为map,根据map读取json的某个数据,可以读取第一级的数据name,后来发现想转成JsonArray读取”red“时没撤了,只好用了其他方法。
最后用org.json包解决了(readJsonArray函数),有空再看看有没有更好的办法。
JSON文件如下:
{
"name":"name",
"id":"id",
"color":[
{"red":"red","blue":"blue"},
{"white":"white"}
]
}
代码如下:
packagecom;
importorg.codehaus.jackson.map.ObjectMapper;
importorg.json.JSONArray;
importorg.json.JSONObject;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importjava.io.*;
importjava.util.Map;
/**
*Helloworld!
*
*/
publicclassJsonAnalysis
{
privatestaticfinalLoggerLOG=LoggerFactory.getLogger(JsonAnalysis.class);
publicstaticvoidmain(String[]args)throwsFileNotFoundException{
StringjsonString="{\"address\":\"address\",\"name\":\"name\",\"id\":\"1\",\"email\":\"email\"}";
FileReaderfileReader=newFileReader("E:\\JsonAnalysis\\src\\test.json");
StringfileString=readFile(fileReader);
//Json字符串转java对象,比如转为Map对象读取其中数据
Mapmap=null;
MapmapFile=null;
try{
map=readValue(jsonString,Map.class);
mapFile=readValue(fileString,Map.class);
}catch(Exceptione){
e.printStackTrace();
LOG.error("ReadValueoccurexceptionwhenswitchjsonstringtomap");
}
System.out.println(map!=null?map.get("id"):null);
if(mapFile==null){
LOG.info("Jsonmapformfileisempty");
return;
}
System.out.println(mapFile.get("name"));
try{
readJsonArray(fileString);
}catch(Exceptione){
e.printStackTrace();
}
}
//Jsonstringtoobject
privatestaticTreadValue(StringjsonStr,ClassvalueType)throwsException{
ObjectMapperobjectMapper=newObjectMapper();
try{
//Objectobject=objectMapper.readValue(jsonStr,Object.class);
returnobjectMapper.readValue(jsonStr,valueType);
}catch(IOExceptione){
e.printStackTrace();
}
returnnull;
}
//Readfileandtostring
privatestaticStringreadFile(FileReaderfileReader){
BufferedReaderbufferedReader=newBufferedReader(fileReader);
StringBuilderfileStr=newStringBuilder();
try{
StringeachLine;
while((eachLine=bufferedReader.readLine())!=null){
fileStr.append(eachLine);
}
returnfileStr.toString();
}catch(IOExceptione1){
e1.printStackTrace();
LOG.error("Occurexceptionwhenreadfile,file={}",fileReader);
returnnull;
}
}
//根据jsonstring获取jsonarray,读取数据(注意该部分引用的是org.json包)
privatestaticvoidreadJsonArray(StringjsonStr)throwsException{
JSONObjectjsonObject=newJSONObject(jsonStr);
JSONArrayjsonArray=jsonObject.getJSONArray("color");
JSONObjectjsonObject1=jsonArray.getJSONObject(0);
System.out.println(jsonObject1.get("red"));
}
}
以上这篇Jackson将jsonstring转为Object,org.json读取json数组的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。