这篇文章主要介绍了Java 从json提取出数组并转换为list,使用getJSONArray()获取到jsonarray后,再将jsonArray转换为字符串,最后将字符串解析为List列表,本文通过实例代码给大家详细讲解,需要的朋友可以参考下
// 解析为JSONObject
JSONObject jsonObject = JSONObject.parseObject(ret);
// 提取出JSONArray
JSONArray jsonArray = new JSONArray(jsonObject.getJSONObject("result").getJSONArray("org_list"));
// 将JSONArray转为List列表
String str = JSONObject.toJSONString(jsonArray);
List<Org> list = JSONObject.parseArray(str, Org.class);
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import com.css.eshop.exception.DataAccessException;
import com.css.eshop.model.VoucherInfo;
import com.css.eshop.util.HttpClientUtil;
import com.css.eshop.util.LoadStaticReferenceTables;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestPut {
protected Log logger = LogFactory.getLog(this.getClass().getName());
@Test
public void getOneJson(){//测试转换成Json,单个对象
VoucherInfo vo1=new VoucherInfo();
vo1.setVoucherValue(2131);vo1.setVoucherCode("小可爱的");
JSONObject updateJsonObj = JSONObject.fromObject(vo1);//转换成json格式
logger.info("---转换成json格式:---"+updateJsonObj.toString());//提取access_token节点数据
输出转换后日志:
17-10-2018 17:35 INFO TestPut:35 - ---转换成json格式:---{"labourCost":0,"refMetalPrice":0,"voucherCoNumber":"","voucherCode":"小可爱的","voucherType":"","voucherValue":2131,"weight":0,"weightUnit":""}
(二)多个对象存到List,再转换成JSON
@Test
public void getArrayList(){//测试转换成Json,List转换成JSONList
List<VoucherInfo> vouchersList=new ArrayList<VoucherInfo>();
VoucherInfo vo1=new VoucherInfo();
VoucherInfo vo2=new VoucherInfo();
vo1.setVoucherValue(2131);vo1.setVoucherCode("小可爱的");
vo2.setVoucherValue(100);vo2.setVoucherCode("小可爱的222");
vouchersList.add(vo1);vouchersList.add(vo2);
JSONArray jsonArray = JSONArray.fromObject(vouchersList);
logger.info("--获取到转换为json格式的内容:"+jsonArray.toString());//提取access_token节点数据
输出日志:
17-10-2018 17:36 INFO TestPut:47 - --获取到转换为json格式的内容:[{"labourCost":0,"refMetalPrice":0,"voucherCoNumber":"","voucherCode":"小可爱的","voucherType":"","voucherValue":2131,"weight":0,"weightUnit":""},{"labourCost":0,"refMetalPrice":0,"voucherCoNumber":"","voucherCode":"小可爱的222","voucherType":"","voucherValue":100,"weight":0,"weightUnit":""}]
(三)json的list对象转List对象
先转jsonArray,再转object提取数据