在www.json.org上公布了很多Java下的json解析工具,其中org.json和json-lib比较简单,两者使用上差不多。下面两段源代码是分别使用这两个工具解析和构造JSON的演示程序。
1.org.json解析Json的过程.json.jar见附件
TestJson.java如下:
package com; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class TestJson { public static void main(String[] args) throws JSONException { // 组Json串 String json = "{\"name\":\"reiz\"}"; // 根据Json串生成Json对象 JSONObject jsonObj = new JSONObject(json); // 获得name键对应的值. String name = jsonObj.getString("name"); System.out.println(name) ; // 输出 reiz // 向Json中追加一个R字符串.initial:R jsonObj.put("initial", name.substring(0, 1).toUpperCase()); // 向Json对象中加入对象类型数据(map) Map<String, String> ingredients = new HashMap<String, String>(); ingredients.put("apples", "3kg"); ingredients.put("sugar", "1kg"); ingredients.put("pastry", "2.4kg"); ingredients.put("bestEaten", "outdoors"); jsonObj.put("ingredients", ingredients); // 获得Map对象的字符串 String ingre = jsonObj.getString("ingredients"); System.out.println(ingre) ; // 输出 {"apples":"3kg","sugar":"1kg","bestEaten":"outdoors","pastry":"2.4kg"} // 把Map对象生成Json对象 JSONObject jsonIngre = new JSONObject(ingre); System.out.println(jsonIngre.getString("apples")) ; // 输出 3kg System.out.println(jsonObj); // 输出 {"ingredients":{"apples":"3kg","sugar":"1kg","bestEaten":"outdoors","pastry":"2.4kg"},"initial":"R","name":"reiz"} } }
2.利用json-lib实现Json的解析,在网上看到的,留以后使用.见json-lin附件.
import java.util.HashMap; import java.util.Map; import net.sf.json.JSONObject; public class Test { public static void main(String[] args) { String json = "{\"name\":\"reiz\"}"; JSONObject jsonObj = JSONObject.fromObject(json); String name = jsonObj.getString("name"); jsonObj.put("initial", name.substring(0, 1).toUpperCase()); String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" }; jsonObj.put("likes", likes); Map<String, String> ingredients = new HashMap<String, String>(); ingredients.put("apples", "3kg"); ingredients.put("sugar", "1kg"); ingredients.put("pastry", "2.4kg"); ingredients.put("bestEaten", "outdoors"); jsonObj.put("ingredients",ingredients); System.out.println(jsonObj); } }