Java读取json文件

  1. 基础知识
    https://www.w3school.com.cn/json/json_syntax.asp
  2. 下载org.json
    org.json的官网: http://www.json.org/java/index.html。点击官网页面的”Free source code is available”,即可转到org.json在github的源码页,点击页面右侧的”Download ZIP”,下载”JSON-java-master.zip”文件,解压该文件。在Eclipse中新建package,命名”org.json”,然后将”JSON-java-master”里的文件拷到”org.json”,即可在项目使用json.
    也可以将org.json打成jar包,方便以后使用。右键org.json文件—Export—Java—JAR file,点”Next”,选中org.json、org.json.zip文件夹,然后输入jar文件的输出路径
  3. 具体实现
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import org.apache.commons.io.FileUtils;
import java.io.File;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
    public static void ReadJs() throws IOException {
     
        File file = new File("originalLocation.json");
        String content = FileUtils.readFileToString(file, "UTF-8");
        JSONObject jsObj = new JSONObject(content);
        JSONArray users = jsObj.getJSONArray("original_location_info");
        JSONObject uti = (JSONObject)(users.get(0));
        int uid = uti.getInt("uid");
        JSONArray traceInfo = uti.getJSONArray("trace_info");
        JSONObject tc = (JSONObject)(traceInfo.get(0));
        int t = tc.getInt("time");
        int cid = tc.getInt("cid");
        System.out.println("ok " + uid + " " + t + " " + cid);
        // users.length()
    }
``

你可能感兴趣的:(java)