1、将各种对象转化为json串
<span style="font-size: 14px;">public static void main(String[] args){
boolean[] newArray = new boolean[]{true,false,true}; //转化boolean型数组
JSONArray json = JSONArray.fromObject(newArray);
System.out.println(json);
List<String> list = new ArrayList<String>();
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<String, String> map = new HashMap<String, String>();
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);
</span>OpenApiForm form1 = (OpenApiForm)JSONObject.toBean(json5,OpenApiForm.class);//将JSON串转化为java bean
System.out.println(form1.getOrderNo());
System.out.println(form1.getUserId());<span style="font-size: 14px;">
</span><span style="font-size: 14px;">}</span>
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<Object> list = new ArrayList<Object>();
Map<String, Long> map1 = new HashMap<String, Long>();
Map<String, Long> map2 = new HashMap<String, Long>();
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
}