当前位置: 首页 > 工具软件 > JSON.simple > 使用案例 >

JSON.simple example – Read and write JSON Read

柴意智
2023-12-01

JSON.simple, is a simple Java library for JSON processing, read and write JSON data and full compliance with JSON specification (RFC4627).

downloaded jar json-simple-1.1.1.jar.

Write JSON to file:

import java.io.File;  
import java.io.FileWriter;  
import java.io.IOException;  
  
import org.json.simple.JSONArray;  
import org.json.simple.JSONObject;  
  
/* 
 * @Author : Arpit Mandliya 
 */  
public class JSONSimpleWritingToFileExample {  
  
    public static void main(String[] args) {  
  
        JSONObject countryObj = new JSONObject();  
        countryObj.put("Name", "India");  
        countryObj.put("Population", new Integer(1000000));  
  
        JSONArray listOfStates = new JSONArray();  
        listOfStates.add("Madhya Pradesh");  
        listOfStates.add("Maharastra");  
        listOfStates.add("Rajasthan");  
  
        countryObj.put("States", listOfStates);  
  
        try {  

            File file=new File("E:\\CountryJSONFile.json");  
            file.createNewFile();  
            FileWriter fileWriter = new FileWriter(file);  
            fileWriter.write(countryObj.toJSONString());  
            fileWriter.flush();  
            fileWriter.close();  
  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
    }  
}

Read JSON to file:

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;  
/* 
 * @Author : Arpit Mandliya 
 */  
public class JSONSimpleReadingFromFileExample {  
  
 public static void main(String[] args) {  
  
  JSONParser parser = new JSONParser();  
  
  try {  
  
   Object obj = parser.parse(new FileReader("E:\\CountryJSONFile.json"));  
  
   JSONObject jsonObject = (JSONObject) obj;  
  
   String nameOfCountry = (String) jsonObject.get("Name");  
   System.out.println("Name Of Country: "+nameOfCountry);  
  
   long population = (Long) jsonObject.get("Population");  
   System.out.println("Population: "+population);  
  
   System.out.println("States are :");  
   JSONArray listOfStates = (JSONArray) jsonObject.get("States");  
   Iterator<String> iterator = listOfStates.iterator();  
   while (iterator.hasNext()) {  
    System.out.println(iterator.next());  
   }  
  
  } catch (FileNotFoundException e) {  
   e.printStackTrace();  
  } catch (IOException e) {  
   e.printStackTrace();  
  } catch (ParseException e) {  
   e.printStackTrace();  
  }  
  
 }  
}


 类似资料:

相关阅读

相关文章

相关问答