java读取JSON文件

读前需要了解

首先我用到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

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值