从json文件读取json string或者自定义json string,将其转为object。下面采用的object为map,根据map读取json的某个数据,可以读取第一级的数据name,后来发现想转成JsonArray读取”red“时没撤了,只好用了其他方法。
最后用org.json包解决了(readJsonArray函数),有空再看看有没有更好的办法。
JSON文件如下:
1
2
3
4
5
6
7
8
|
{
"name":"name",
"id":"id",
"color":[
{"red":"red","blue":"blue"},
{"white":"white"}
]
}
|
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
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数组的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/ilovena/archive/2017/12/11/8023305.html