1、将各种对象转化为json串
public static void main(String[] args){
boolean[] newArray = new boolean[]{true,false,true}; //转化boolean型数组
JSONArray json = JSONArray.fromObject(newArray);
System.out.println(json);
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray2 = JSONArray.fromObject( list ); //转化list对象
System.out.println( jsonArray2 );
JSONArray jsonArray3 = JSONArray.fromObject( "['json','is','easy']" );//转化字符串对象
System.out.println( jsonArray3 );
Map map = new HashMap();
map.put("key","json");
map.put("test", "test");
JSONObject json4 = JSONObject.fromObject(map);//转化map对象
System.out.println(json4);
OpenApiForm form = new OpenApiForm();
form.setUserId("100");
form.setOrderNo("123ABC");
JSONObject json5 = JSONObject.fromObject(form);//将bean转为JSON
System.out.println(json5);
OpenApiForm form1 = (OpenApiForm)JSONObject.toBean(json5,OpenApiForm.class);//将JSON串转化为java bean
System.out.println(form1.getOrderNo());
System.out.println(form1.getUserId());
}
2、生成指定格式的字符串,获取JSON串中的数据
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
List list = new ArrayList();
Map map1 = new HashMap();
Map map2 = new HashMap();
Long userid=12311l;
map1.put("goodsid", 7098l);
map1.put("goodscount", 12l);
map2.put("goodsid", 32l);
map2.put("goodscount", 2l);
list.add(map1); list.add(map2); JSONArray jsonObj=JSONArray.fromObject(list); //将list转化为JSONArray对象 String goodsInfo="{goodsInfo:"+jsonObj.toString()+",userId:"+userid+"}"; JSONObject obj=JSONObject.fromObject(goodsInfo); System.out.println(obj); System.out.println(obj.getJSONArray("goodsInfo").getJSONObject(0).get("goodsid"));//获取json串中goodsid System.out.print(obj.get("userId"));//获取json中数据userId }