java——读取JSON文件

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

就搜索些视频、博客看了一下,这里整理一番。

读前需要了解

  • java-IO 基础知识
  • java-File了解
  • 推荐一篇博文:使用FileUtils简化你的文件操作

首先我用到Apache Common IO 2.5包和java-JSON包

注意:
java-JSON包可以先在 github 下载下来,然后用 eclipse 将里面的java文件打包为 jar文件,在添加在需要的程序中去。如果用 Maven ,就添加依赖就行。

这里通过一个简单的例子讲解一下吧,若我收到的 JSON 文件内容如下

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

思路过程:

  1. 获取文件
  2. 获取文件内容
  3. 转换为 JSON 对象
  4. 读取 JSON 对象

具体java代码实现如下:

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"));

    }
}

大 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) {
        ...
    }
}

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

其中 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 {
        ...
    }
}

文中有什么错误,有好的方法。若有时间,请你告诉我,也虚心学习一番。祝你好运!

参考资料:
1. Parsing a large JSON file efficiently and easily
2. Reading very big JSON files in stream mode with GSON

你可能感兴趣的:(java)