JSON with Java
本章介绍如何使用Java编程语言对JSON对象进行编码和解码。 让我们从准备环境开始,使用Java for JSON开始编程。
环境 (Environment)
在开始使用Java编码和解码JSON之前,您需要安装任何可用的JSON模块。 在本教程中,我们已经下载并安装了JSON.simple ,并将json-simple-1.1.1.jar文件的位置添加到环境变量CLASSPATH中。
JSON和Java实体之间的映射
JSON.simple在解码或解析时将实体从左侧映射到右侧,并在编码时将实体从右侧映射到左侧。
JSON | Java的 |
---|---|
string | java.lang.String |
number | java.lang.Number |
true|false | java.lang.Boolean |
null | null |
array | java.util.List |
object | java.util.Map |
在解码时, java.util.List的默认具体类是org.json.simple.JSONObject , java.util.Map的默认具体类是org.json.simple.JSONObject 。
在Java中编码JSON
以下是使用Java JSONObject编码JSON对象的简单示例,Java JSONObject是java.util.HashMap的子类。 没有提供订购。 如果需要严格的元素排序,请使用带有序映射实现的JSONValue.toJSONString(map)方法,例如java.util.LinkedHashMap。
import org.json.simple.JSONObject;
class JsonEncodeDemo {
public static void main(String[] args){
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
System.out.print(obj);
}
}
在编译和执行上述程序时,将生成以下结果 -
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}
以下是另一个使用Java JSONObject显示JSON对象流的示例 -
import org.json.simple.JSONObject;
class JsonEncodeDemo {
public static void main(String[] args){
JSONObject obj = new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
}
}
在编译和执行上述程序时,会生成以下结果 -
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}
用Java解码JSON
以下示例使用JSONObject和JSONArray ,其中JSONObject是java.util.Map,JSONArray是java.util.List,因此您可以使用Map或List的标准操作来访问它们。
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
class JsonDecodeDemo {
public static void main(String[] args){
JSONParser parser = new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println("The 2nd element of array");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2 = (JSONObject)array.get(1);
System.out.println("Field \"1\"");
System.out.println(obj2.get("1"));
s = "{}";
obj = parser.parse(s);
System.out.println(obj);
s = "[5,]";
obj = parser.parse(s);
System.out.println(obj);
s = "[5,,2]";
obj = parser.parse(s);
System.out.println(obj);
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
}
在编译和执行上述程序时,将生成以下结果 -
The 2nd element of array
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}
Field "1"
{"2":{"3":{"4":[5,{"6":7}]}}}
{}
[5]
[5,2]
<上一篇.JSON with Ruby
JSON with Ajax.下一篇>