Java读取JSON文件主要是利用JSON分析库来完成的,常用的库有JSON-lib,Gson,Jackson等。这些库提供了一种简单的编码和解码JSON文本的方法,允许将JSON文本转换为Java对象,或将Java对象转换为JSON文本。
一、使用JSON-lib读取JSON文件
JSON-lib库是一个为Java对象提供json编解码的API,它还可以将Javacolections转换为json对象,或转换XML文档数据。
import net.sf.json.JSONObject;
import java.io.BufferedReader;
import java.io.FileReader;
public class ReadJsonSample {
public static void main(String[] args) {
StringBuilder jsonStr = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader("file.json"));
String str;
while ((str = in.readLine()) != null) {
jsonStr.append(str);
}
in.close();
} catch (IOException e) {
e.getStackTrace();
}
System.out.println("The JSON File content is:\n" + jsonStr.toString());
JSONObject jsonObject = JSONObject.fromObject(jsonStr.toString());
System.out.println("The JSON Object is:\n" + jsonObject);
}
}二、使用Gson库读取JSON文件
谷歌的Gson库也是一个强大的json处理库,通过Gson,我们可以将json字符串转换为强类型的Java对象,也可以将Java对象转换为json字符串。
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class ReadJsonSample {
public static void main(String[] args) {
Gson gson = new Gson();
try {
Reader reader = new FileReader("file.json");
JsonReader jsonReader = new JsonReader(reader);
SampleObject object = gson.fromJson(jsonReader, SampleObject.class);
System.out.println(object);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}三、使用Jackson库读取JSON文件
Jackson是一种库,可以将Java对象转换为Java对象,同时也可以将Java对象转换为Java对象。
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
public class ReadJsonSample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
User user = mapper.readValue(new File("file.json"), User.class);
System.out.println(user.getName());
System.out.println(user.getAge());
} catch (IOException e) {
e.printStackTrace();
}
}
} 本文链接:https://my.lmcjl.com/post/20171.html
展开阅读全文
4 评论