Hot For Coding
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>

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: 转载内容请注明出处