繁体   English   中英

如何从 Java 中的 JSON 文件中读取数据

[英]How to read from a JSON file in Java

我整夜都在寻找,但找不到任何适合我的东西。

我正在尝试用 Java 读取和解析 JSON 文件。 我尝试了我找到的所有代码,但没有一个对我有用。 我将不胜感激您的帮助。

所以这是代码:

public void parseJSONData() {

    clearData();

    try {
        FileInputStream in = openFileInput(getFilesDir()
                + "/tbl_category.json");
        InputStreamReader inputStreamReader = new InputStreamReader(in);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }

我正在使用getFilesDir() + "/tbl_category.json"因为应用程序在启动时会在 /data/data/com.the.restaurant/files/ 下载some.json文件。

这是课程的其余部分:

        // parse json data and store into arraylist variables
        JSONObject json = new JSONObject(line);
        JSONArray data = json.getJSONArray("data");

        for (int i = 0; i < data.length(); i++) {
            JSONObject object = data.getJSONObject(i);

            JSONObject category = object.getJSONObject("Category");

            Category_ID.add(Long.parseLong(category
                    .getString("Category_ID")));
            Category_name.add(category.getString("Category_name"));
            Category_image.add(category.getString("Category_image"));
            Log.d("Category name", Category_name.get(i));

        }

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        IOConnect = 1;
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

我刚刚开始学习 Java,非常感谢您的帮助!

代替

 JSONObject json = new JSONObject(line);

将读取的最后一行转换为 JSON 对象(并且可能失败),您需要

 JSONObject json = new JSONObject(sb.toString());

这将采用行的串联( StringBuilder的内容)

在这一行中,您只阅读一行来创建 JSON 对象。

 JSONObject json = new JSONObject(line);

它应该使用包含整个 JSON 字符串的StringBuilder

 JSONObject json = new JSONObject(sb.toString());
    val inputStream: InputStream = context.assets.open(fileName)
    dataDetails = inputStream.bufferedReader().use{it.readText()}

    // now we create a json object and read the values
    val jsonObject = JSONObject(dataDetails)

    // if you know that is a number you can get it like this
    var age = jsonObj.getInt("person_age")

    // the same for boolean
    var someBooleanValue = jsonObj.getBoolean("person_married")

    // for an array
    val jsonArrayLabels = jsonObj.getJSONArray("simpleArray")
    
    //If you know what type you have to get use the function for that type, 
    //so you can save them and later do manipulations with them  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM