java生成JSON串

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
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值