JSON.simple是用于JSON处理,读取和写入JSON数据并完全符合JSON规范(RFC4627)的简单Java库。
1.下载JSON.simple
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
2.将JSON写入文件
package com.mkyong;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.FileWriter;
import java.io.IOException;
public class JsonSimpleWriteExample {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("name", "mkyong.com");
obj.put("age", 100);
JSONArray list = new JSONArray();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");
obj.put("messages", list);
try (FileWriter file = new FileWriter("c:\\projects\\test.json")) {
file.write(obj.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
}
输出量
{"name":"mkyong.com","messages":["msg 1","msg 2","msg 3"],"age":100}
{"name":"mkyong.com","messages":["msg 1","msg 2","msg 3"],"age":100}
3.读取JSON到文件
package com.mkyong;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
public class JsonSimpleReadExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try (Reader reader = new FileReader("c:\\projects\\test.json")) {
JSONObject jsonObject = (JSONObject) parser.parse(reader);
System.out.println(jsonObject);
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);
// loop array
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
输出量
{"name":"mkyong.com","messages":["msg 1","msg 2","msg 3"],"age":100}
mkyong.com
100
msg 1
msg 2
msg 3
参考文献
- JSON.simple 3.x主页
- JSON.simple 1.x主页
- JSON.simple 1.x Google主页
- JSON.simple 1.x编码示例
- JSON.simple 1.x解码示例
- Gson –如何设置JSON
- 杰克逊–如何解析JSON
- JSON.simple 3.x –如何解析JSON
翻译自: https://mkyong.com/java/json-simple-example-read-and-write-json/