Java 处理json经常使用代码

Java 处理json经常使用代码

大家好,又见面了,我是全栈君。

本project代码已上传至资源,如有须要,请自行下载。
package com.michael;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.PropertyUtils;
import org.junit.Test;

public class JsonLibTest {
	/**
	 * 将数组转换为json对象
	 */
	// @Test
	public void testArrayToJSON() {
		boolean[] boolArray = new boolean[] { true, false, true };
		JSONArray jsonArray = JSONArray.fromObject(boolArray);
		System.out.println("testArrayToJSON----jsonArray-----" + jsonArray);
	}

	/**
	 * 将集合转换为json
	 */
	// @Test
	public void testListToJSON() {
		List<String> list = new ArrayList<String>();
		list.add("first");
		list.add("second");
		JSONArray jsonArray = JSONArray.fromObject(list);
		System.out.println("testListToJSON---jsonArray----" + jsonArray);
	}

	/**
	 * 将json字符串转换为json对象
	 */
	@Test
	public void testJsonStrToJSON() {
		JSONArray jsonArray = JSONArray.fromObject("['json','is','easy']");
		System.out.println("testJsonStrToJSON---jsonArray----" + jsonArray);
	}

	/**
	 * 将map转换为json对象
	 */
	@Test
	public void testMapToJSON() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", "json");
		map.put("bool", Boolean.TRUE);
		map.put("int", new Integer(1));
		map.put("arr", new String[] { "a", "b" });
		map.put("func", "function(i){ return this.arr[i]; }");
		JSONObject jsonObject = JSONObject.fromObject(map);
		System.out.println("testJsonStrToJSON---jsonObject----" + jsonObject);
	}

	// 将实体类转换为json
	@Test
	public void testBeadToJSON() {
		Car bean = new Car();
		bean.setId("001");
		bean.setName("hello");
		bean.setDate(new Date());

		List<Car> cars = new ArrayList<Car>();
		cars.add(new Car("AUDI"));
		cars.add(new Car("BMW"));
		cars.add(new Car("QQ"));
		// cars.add(new Person("test"));
		bean.setCars(cars);
		JSONObject jsonObject = JSONObject.fromObject(bean);
		System.out.println("testBeadToJSON---jsonObject----" + jsonObject);

	}

	@Test
	/**
	 * 将json字符串转换为对象
	 * @throws Exception
	 */
	public void testJSONToObject() throws Exception {
		String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
		JSONObject jsonObject = JSONObject.fromObject(json);
		Object bean = JSONObject.toBean(jsonObject);
		assertEquals(jsonObject.get("name"),
				PropertyUtils.getProperty(bean, "name"));
		assertEquals(jsonObject.get("bool"),
				PropertyUtils.getProperty(bean, "bool"));
		assertEquals(jsonObject.get("int"),
				PropertyUtils.getProperty(bean, "int"));
		assertEquals(jsonObject.get("double"),
				PropertyUtils.getProperty(bean, "double"));
		assertEquals(jsonObject.get("func"),
				PropertyUtils.getProperty(bean, "func"));

		List arrayList = (List) JSONArray.toCollection(jsonObject
				.getJSONArray("array"));
		for (Object object : arrayList) {
			System.out.println(object);
		}

	}
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/115940.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 秒懂mysql中的group by用法

    秒懂mysql中的group by用法文章转载自:https://blog.csdn.net/u014717572/article/details/80687042先来看下表1,表名为test:执行如下SQL语句:SELECTnameFROMtestGROUPBYname你应该很容易知道运行的结果,没错,就是下表2:可是为了能够更好的理解“groupby”多个列“和”聚合函数“的应用,我建议在思考的过程中…

    2022年5月26日
    44
  • Java——JDBC连接数据库(步骤详解!!!)

    Java——JDBC连接数据库(步骤详解!!!)JDBC的全称是:JavaDatabaseConnectivity,即Java数据库连接。JDBC可以通过载入不同的数据库的“驱动程序”而与不同的数据库进行连接。那么,在数据库连接的时候,我使用的是MySQL,Java集成开发环境是Eclipse。要使用JDBC来访问MySQL数据库,首先需要添加MySQL数据库驱动程序。下面,我来为大家讲解一下这其中的步骤(听着名字很高大上,但仔细看步骤会觉得其实没那么难!!!)????????????Step1:www.mysql.co

    2022年7月26日
    12
  • jdbctemplate.query_query方法

    jdbctemplate.query_query方法Document.querySelectorAllSummaryReturnsalistoftheelementswithinthedocument(usingdepth-firstpre-ordertraversalofthedocument’snodes)thatmatchthespecifiedgroupofselectors….

    2025年7月6日
    0
  • 网络:下载进度条

    网络:下载进度条#import”ViewController.h”#import”ProgressButton.h”@interfaceViewController()@property(nonatomic,assign)longlongfileSize;//文件总大小@property(nonatomic,assign)

    2022年7月14日
    12
  • qt的内存映射

    qt的内存映射uchar*QFileDevice::map(qint64offset,qint64size,QFileDevice::MemoryMapFlagsflags=NoOptions)从偏移量开始将文件的大小字节映射到内存中。应该打开一个文件以使映射成功,但在映射内存之后,该文件不需要保持打开状态。当QFile被销毁或用这个对象打开一个新文件时,任何未被映射的映射都将被自动取消映射。映射将具有与文件相同的打开模式(读和/或写),除非使用maprivateOption,在这种情况下,始终可以

    2022年6月15日
    107
  • eidos云矿机_空投挖矿

    eidos云矿机_空投挖矿eidos空投矿机虽然已经有几款网页版的了,甚至还有收费的,但并不适合长期运行,特别是需要挂在VPS里,所以就出现了这款控制台运行的,如果觉得对你有帮助就给个star吧。项目地址https://github.com/donjan-deng/eidos-miner环境需求nodejs>=10scatter>=11(网页版可在低版本运行)使用方法也有个简易的网页版…

    2022年9月30日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号