Java解析JSON

推荐使用com.googlecode.json-simple依赖包,先在pom.xml添加依赖

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
  <groupId>com.googlecode.json-simple</groupId>
  <artifactId>json-simple</artifactId>
  <version>1.1.1</version>
</dependency>

【国内直连ChatGPT 29元起】
国内直连ChatGPT,Plus会员每月29元起,支持最新o1模型探索更多领域,无需注册OpenAI账号。

example.json

[
  {
    "employee": {
      "firstName": "Lucy",
      "lastName": "Lee",
      "website": "lucy.com"
    }
  },
  {
    "employee": {
      "firstName": "Aka",
      "lastName": "Lee",
      "website": "example.com"
    }
  }
]

读取json文件,并解析

readjson.java

package com.nicholaslee.demo.readjson;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
 
public class ReadJSON
{
  @SuppressWarnings("unchecked")
  public static void main(String[] args)
  {
    //JSON parser object to parse read file
    JSONParser jsonParser = new JSONParser();
      
    try (FileReader reader = new FileReader("example.json"))
    {
      //Read JSON file
      Object obj = jsonParser.parse(reader);

      JSONArray employeeList = (JSONArray) obj;
      System.out.println(employeeList);
        
      //Iterate over employee array
      employeeList.forEach( emp -> parseEmployeeObject( (JSONObject) emp ) );

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

  private static void parseEmployeeObject(JSONObject employee)
  {
    //Get employee object within list
    JSONObject employeeObject = (JSONObject) employee.get("employee");
      
    //Get employee first name
    String firstName = (String) employeeObject.get("firstName");   
    System.out.println(firstName);
      
    //Get employee last name
    String lastName = (String) employeeObject.get("lastName"); 
    System.out.println(lastName);
      
    //Get employee website name
    String website = (String) employeeObject.get("website");   
    System.out.println(website);
  }
}

要根据内容读入数据时判断好使用JSONObject还是JSONArray

分享

TITLE: Java解析JSON

LINK: https://www.qttc.net/391-java-read-json-file.html

NOTE: 原创内容,转载请注明出自琼台博客