Java JSON示例
json.simple 库允许我们在Java中读取和写入JSON数据。换句话说,我们可以使用json.simple库在Java中对JSON对象进行编码和解码。
org.json.simple包中包含JSON API的重要类。
JSONValue
JSONObject
JSONArray
JsonString
JsonNumber
安装json.simple
要安装json.simple,您需要设置json-simple.jar的类路径或添加Maven依赖项。
1)下载json-simple.jar 或
2)要添加Maven依赖关系,请编写pom.xml文件中的以下代码。
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
1)Java JSON编码
让我们看一个简单的示例,用Java对JSON对象进行编码。
import org.json.simple.JSONObject;
public class JsonExample1{
public static void main(String args[]){
JSONObject obj=new JSONObject();
obj.put("name","sonoo");
obj.put("age",new Integer(27));
obj.put("salary",new Double(600000));
System.out.print(obj);
}}
输出:
{"name": " sonoo","age": 27,"salary": 600000.0}
使用Map进行Java JSON编码
让我们看一个使用Java中的map来编码JSON对象的简单示例。
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONValue;
public class JsonExample2{
public static void main(String args[]){
Map obj=new HashMap();
obj.put("name","sonoo");
obj.put("age",new Integer(27));
obj.put("salary",new Double(600000));
String jsonText = JSONValue.toJSONString(obj);
System.out.print(jsonText);
}}
输出:
{"name": " sonoo","age": 27,"salary": 600000.0}
Java JSON数组编码
让我们看一个简单的示例,用Java对JSON数组进行编码。
import org.json.simple.JSONArray;
public class JsonExample1{
public static void main(String args[]){
JSONArray arr = new JSONArray();
arr.add("sonoo");
arr.add(new Integer(27));
arr.add(new Double(600000));
System.out.print(arr);
}}
输出:
使用列表对Java JSON数组进行编码
让我们看一个简单的示例,使用Java中的列表对JSON数组进行编码。
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONValue;
public class JsonExample1{
public static void main(String args[]){
List arr = new ArrayList();
arr.add("sonoo");
arr.add(new Integer(27));
arr.add(new Double(600000));
String jsonText = JSONValue.toJSONString(arr);
System.out.print(jsonText);
}}
输出:
2)Java JSON解码
让我们看一个用Java解码JSON字符串的简单示例。
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JsonDecodeExample1 {
public static void main(String[] args) {
String s="{\"name\":\"sonoo\",\"salary\":600000.0,\"age\":27}";
Object obj=JSONValue.parse(s);
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
double salary = (Double) jsonObject.get("salary");
long age = (Long) jsonObject.get("age");
System.out.println(name+" "+salary+" "+age);
}
}
输出: