json - 我们如何读取 JSON 文件
问题描述
从文件服务器读取 JSON 文件的实用程序 2. 实用程序应在预定时间运行,比如早上 6 点 3. 如果 JSON 文件格式不正确,则会出现错误消息 4. 如果类别丢失且 ITEM 需要保存该类别,则会出现错误消息。5. 根据数据模型中的给定关系进行实体映射 5. API 文档,最好使用任何工具 6. 使用 Mockito 的 Junit 测试用例 7. 使用 MySQL 或 Oracle 进行 API 开发 8. 添加一个点作为 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
谢谢
推荐阅读
- java - 我如何自己获得像“start.spring.io”这样的springboot项目
- razor - Umbraco Embed URL not working 会抛出错误 ould not embed media - 请确保 URL 有效
- twilio - 示例代码项目无法编译
- apache - 基于 TSL/SSL 的 HTTP CONNECT 握手
- airflow - 有人可以帮我启动 apache 气流吗?
- django - 如何为 Apache 提供的 django 应用程序将 http url 重定向到 https
- asp.net-mvc - 如何在 ViewModel 中添加两个连续的 Display 语法?
- sql - 通过比较和检索涉及多列的数据的 SQL INSERT 语句
- image-processing - imagemagick mogrify 调整大小 - 失去第三维
- python - 仅使用脚本中的一列,但也打印同一索引的另一列