在开发过程中我们经常需要使用json格式的数据来传递信息,前段时间写的一个小demo在此整理一下做个笔记。
1、将各种对象转化为json串
?
class="java" name="code">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); 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<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 }
?程序运行结果:
生成json串的格式:
?
?
?