string转化为json
1 import org.json.JSONArray; 2 import org.json.JSONException; 3 import org.json.JSONObject; 4 5 //别忘了添加上JSON包哦! 6 public class StringToJSON { 7 public static void main(String[] args) throws JSONException{ 8 9 System.out.println("abc"); 10 //定义JSON字符串 11 String jsonStr = "{\"id\": 2," + 12 " \"title\": \"json title\", " + 13 "\"config\": {" + 14 "\"width\": 34," + 15 "\"height\": 35," + 16 "}, \"data\": [" + 17 "\"JAVA\", \"JavaScript\", \"PHP\"" + 18 "]}"; 19 20 //转换成为JSONObject对象 21 JSONObject jsonObj = new JSONObject(jsonStr); 22 23 //从JSONObject对象中获取数据 24 JavaBean bean = new JavaBean(); 25 26 //根据属性名称获取int型数据; 27 bean.setId(jsonObj.getInt("id")); 28 29 //根据属性名获取String数据; 30 bean.setTitle(jsonObj.getString("title")); 31 32 //根据属性名获取JSONObject类 33 JSONObject config = jsonObj.getJSONObject("config"); 34 bean.setWidth(config.getInt("width")); 35 bean.setHeight(config.getInt("height")); 36 37 //根据属性名获取JSONArray数组 38 JSONArray data = jsonObj.getJSONArray("data"); 39 for(int index = 0, length = data.length(); index < length; index++) { 40 //这里在org.json.JSONArray对象中居然没有找到toArray方法,求各位网友给出解决办法啊! 41 // bean.setLanguages(String[]); 42 } 43 } 44 } 45 46 class JavaBean{ 47 private int id ; 48 private String title; 49 private int width; 50 private int height; 51 private String[] languages; 52 53 //这里省略了设置器和访问器 54 }
json转化为字符串
public static void main(String[] args) throws JSONException { 2 3 //创建JSONObject对象 4 JSONObject json = new JSONObject(); 5 6 //向json中添加数据 7 json.put("username", "wanglihong"); 8 json.put("height", 12.5); 9 json.put("age", 24); 10 11 //创建JSONArray数组,并将json添加到数组 12 JSONArray array = new JSONArray(); 13 array.put(json); 14 15 //转换为字符串 16 String jsonStr = array.toString(); 17 18 System.out.println(jsonStr); 19 }