相关文章推荐
个性的韭菜  ·  android - Show GIF ...·  2 年前    · 
英姿勃勃的勺子  ·  打开MASA ...·  2 年前    · 

我们拿到 JSON 文件,若想通过 java 读取其中的数据,该怎么做呢?

读前必知:

  1. IO 基础知识
  2. FileUtils => IO流 - 使用 FileUtils 简化文件操作

所需JAR包:

  • Apache Common IO
  • Java-JSON
  • GSON(后面大文件用到)

1、针对小JSON文件

{
  "name": "ALemon",
  "age": 24.2,
  "car": null,
  "major":["敲代码","学习"],
  "Nativeplace": {
  "city": "广州",
  "country": "China"
}

思路过程:

  1. 获取文件
  2. 获取文件内容
  3. 转换为 JSON 对象
  4. 读取 JSON 对象
import org.apache.commons.io.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
public class Demo {
    public static void main(String args[]) throws IOException {
        File file=new File("mejson");
        String content= FileUtils.readFileToString(file,"UTF-8");
        JSONObject jsonObject=new JSONObject(content);
        System.out.println("姓名是:"+jsonObject.getString("name"));
        System.out.println("年龄:"+jsonObject.getDouble("age"));
        System.out.println("学到的技能:"+jsonObject.getJSONArray("major"));
        System.out.println("国家:"+jsonObject.getJSONObject("Nativeplace").getString("country"));
}

2、针对大JSON文件

如果您的JSON很小,那么对象模型很好,因为您可以加载所有数据并作为普通Java对象工作。 当文件非常大时 ,您可能不想加载它全部进入内存。

因此流和对象模型之间混合使用模式个人觉得是最佳选择。

Json文件由数组Person对象形成。每个人都有的id,name,married状态和名单sons和daughters:


[
    "id" : 0,
    "married" : true,
    "name" : "George Moore",
    "sons" : null,
    "daughters" : [
        "age" : 25,
        "name" : "Elizabeth"
        "age" : 28,
        "name" : "Nancy"
        "age" : 9,
        "name" : "Sandra"
]

Person 类

public class Person {
    private int id;
    private String name;
    private boolean married;
    // Getter/Setter methods
    @Override
    public String toString() {
        return "Person{" + "id=" + id + ", name=" + name + ... + '}';
}

我们在这里要做的是在流和对象模型之间使用混合模式。我们将以流模式读取文件,每次我们找到一个人物对象时,我们将使用对象模型装配,重复该过程,直到找到所需的对象。

public static void readStream() {
    try {
        JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));
        Gson gson = new GsonBuilder().create();
        // Read file in stream mode
        reader.beginArray();
        while (reader.hasNext()) {
            // Read data into object model
            Person person = gson.fromJson(reader, Person.class);
            if (person.getId() == 0 ) {
                System.out.println("Stream mode: " + person);
                break;
        reader.close();
    } catch (UnsupportedEncodingException ex) {
    } catch (IOException ex) {
}

Ps:JsonReader 需要引入 Gson包。

使用这种方法,我们将所有对象一个接一个地加载到内存而不是整个文件。

其中 stream 为目标文件stream对象。 Gson 的 API 使用可以自行查询。

此外,如果想 一次将json中的内容装配到Person数组 中,可以通过以下方法实现。但此方法会 消耗较多的内存


public static void readDom() {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(file));
        Gson gson = new GsonBuilder().create();
        Person[] people = gson.fromJson(reader, Person[].class);
        System.out.println("Object mode: " + people[0]);
    } catch (FileNotFoundException ex) {
    } finally {