首页 > 解决方案 > 我们如何读取 JSON 文件

问题描述

从文件服务器读取 JSON 文件的实用程序 2. 实用程序应在预定时间运行,比如早上 6 点 3. 如果 JSON 文件格式不正确,则会出现错误消息 4. 如果类别丢失且 ITEM 需要保存该类别,则会出现错误消息。5. 根据数据模型中的给定关系进行实体映射 5. API 文档,最好使用任何工具 6. 使用 Mockito 的 Junit 测试用例 7. 使用 MySQL 或 Oracle 进行 API 开发 8. 添加一个点作为 JSON 验证而不是空值和值范围

谢谢

标签: json

解决方案


我尝试在下面介绍此问题的第一个问题,但不确定如何回答与此问题相关的其余 7 个问题:- 在 eclipse 中创建一个名为“JSONRead”的类。在此我们将使用“JSONParser”将文件中的 JSON 字符串转换为 JSONOBject。为了使用 JSON Parser,请确保您的字符串是 JSON 格式。

enter code here`enter code here`
enter code here
{
package logicProgramming;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonRead {

    public static void main(String[] args) {

        JSONParser parser = new JSONParser();
        //JsonParser to convert JSON string into Json Object

        try {
            Object obj = parser.parse(new FileReader("g:\\newfile.json"));
            //parsing the JSON string inside the file that we created earlier.

            JSONObject jsonObject = (JSONObject) obj;
            System.out.println(jsonObject);
            //Json string has been converted into JSONObject

            String name = (String) jsonObject.get("name");
            System.out.println(name);

            String department = (String) jsonObject.get("department");
            System.out.println(department);

            String branch = (String) jsonObject.get("branch");
            System.out.println(branch);

            long year = (long) jsonObject.get("year");
            System.out.println(year);
            //Displaying values from JSON OBject by using Keys

            JSONArray remarks = (JSONArray) jsonObject.get("remarks");
            //converting the JSONObject into JSONArray as remark was an array.
            Iterator<String> iterator = remarks.iterator();
            //Iterator is used to access the each element in the list 
            //loop will continue as long as there are elements in the array.
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
                //accessing each elemnt by using next function.
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}

enter code here
enter code here

谢谢


推荐阅读