【分享】java与json串的基本操作处理脚本示例
pom文件中的maven坐标<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
</dependency>
java代码示例:
package Study;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
/**
* Created by songwenjun on 2016/7/21.
*/
public class JsonOperate {
//基本的JSONArray与JSONObject操作
@Test
public void JsonObjectAndJsonArray() {
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", "zhangsan");
jsonObj.put("sex", "female");
System.out.println("jsonObj: " + jsonObj); //输出为:{"name":"zhangsan","sex":"female"}
JSONArray jsonArray = new JSONArray();
jsonArray.add("11");
jsonArray.add("22");
jsonArray.add("33");
System.out.println("jsonArray:" + jsonArray); //输出为:["11","22","33"]
}
//由java自带的数据结构转换为JSON文本
@Test
public void JavaDataTypetoJSON() {
//可以由数组,列表等生成JSONArray
String list[] = {"11","22"};
JSONArray jsonArray = JSONArray.fromObject(list);
jsonArray.add("33");
System.out.println("jsonArray: " + jsonArray); //输出为:["11","22","33"]
//可以由Map生成JSONObject
Map<String,Object> map = new HashMap<String,Object>();
map.put("NO1", "第一个");
map.put("NO2", "第二个");
map.put("NO3", jsonArray);
JSONObject jsonObj= JSONObject.fromObject(map);
System.out.println("jsonObj: " + jsonObj); //输出为:{"NO3":["11","22","33"],"NO2":"第二个","NO1":"第一个"}
// JSONArray jsonArray2 = jsonObj.getJSONArray("NO3"); // 根据Key=NO3,获取["11","22","33"]
// System.out.println("GET jsonObj jsonArray2: " + jsonArray2);
}
//读取JSON文本
@Test
public void getJSONValue() {
JSONArray jsonArray;
JSONObject jsonObj;
//读取JSONArray,用下标索引获取(从0开始)
String array = "[\"11\",\"22\",\"33\"]";
System.out.println("String array = " + array);
jsonArray = JSONArray.fromObject(array);
System.out.println("jsonArray.getString(1) = " + jsonArray.getString(1)); //输出为:22
//读取JSONObject
String object = "{\"NO1\":[\"44\",\"55\",\"66\"],\"NO2\":{\"NO1\":\"第一个\"}}";
System.out.println("String object = " + object);
jsonObj = JSONObject.fromObject(object);
System.out.println("jsonObj.get(\"NO1\")" + jsonObj.get("NO1")); //输出为:["44","55","66"]
jsonArray = (JSONArray) (jsonObj.get("NO1"));
System.out.println("jsonArray.getString(1) = " + jsonArray.getString(1)); //输出为:55
//用"键"获取值
jsonObj = (JSONObject) jsonObj.get("NO2");
System.out.println("jsonObj = " + jsonObj); //输出为:{"NO1":"第一个"}
}
}
:victory:
页:
[1]