JSONObject使用方法详解

本文详细介绍了如何使用JSONObject进行json字符串与Java对象、XML字符串之间的转换,包括jsonToJava(), javaToJSON(), jsonToXML(), xmlToJSON()方法的实践,并展示了JavaBean如何转换成JSON和XML。
摘要由CSDN通过智能技术生成

package com.xxh.json;
 
import com.songfayuantools.entity.UserInfo;
 
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
 
/**
 * 描述:JSONObject使用方法详解
 * 	   JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包。
 */
public class Json {
 
	/**
	 * 描述:json字符串转java代码
	 */
	public static void jsonToJava() {
		System.out.println("json字符串转java代码");
		String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
		JSONObject jsonObject = JSONObject.fromObject(jsonStr);
		String username = jsonObject.getString("username");
		String password = jsonObject.getString("password");
		System.err.println("json--->java \n username="+username+"\t passwor="+password);
	}
	
	/**
	 * 描述:java代码封装为json字符串

	 */
	public static void javaToJSON() {
		System.out.println("java代码封装为json字符串");
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("username", "宋发元");
		jsonObject.put("age", 24);
		jsonObject.put("sex", "男");
		System.out.println("java--->json \n " + jsonObject.toString());
	}
	
	/**
	 * 描述:json字符串转xml字符串
	
	 */
	public static void jsonToXML() {
		System.out.println("json字符串转xml字符串");
		String jsonStr = "{\"username\":\"宋发元\",\"password\":\"123456\",\"age\":\"24\"}";
		JSONObject jsonObject = JSONObject.fromObject(jsonStr);
		XMLSerializer xmlSerializer = new XMLSerializer();
		xmlSerializer.setRootName("user_info");
		xmlSerializer.setTypeHintsEnabled(false);
		String xml = xmlSerializer.write(jsonObject);
		System.out.println("json--->xml \n" + xml);
	}
	
	/**
	 * 描述:xml字符串转json字符串
	 
	 */
	public static void xmlToJSON() {
		System.out.println("xml字符串转json字符串");
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><user_info><password>123456</password><username>宋发元</username></user_info>";
		XMLSerializer xmlSerializer = new XMLSerializer();
		JSON json = xmlSerializer.read(xml);
		System.out.println("xml--->json \n" + json.toString());
	}
	
	/**
	 * 描述:javaBean转json字符串
	
	 */
	public static void javaBeanToJSON() {
		System.out.println("javaBean转json字符串");
		UserInfo userInfo = new UserInfo();
		userInfo.setUsername("宋发元");
		userInfo.setPassword("123456");
		JSONObject jsonObject = JSONObject.fromObject(userInfo);
		System.out.println("JavaBean-->json \n" + jsonObject.toString());
	}
	
	/**
	 * 描述:javaBean转xml字符串
	
	 */
	public static void javaBeanToXML() {
		System.out.println("javaBean转xml字符串");
		UserInfo userInfo = new UserInfo();
		userInfo.setUsername("songfayuan");
		userInfo.setPassword("66666");
		JSONObject jsonObject = JSONObject.fromObject(userInfo);
		XMLSerializer xmlSerializer = new XMLSerializer();
		String xml = xmlSerializer.write(jsonObject, "UTF-8");
		System.out.println("javaBean--->xml \n" + xml);
	}
	
	public static void main(String args[]) {
//		jsonToJava();
//		javaToJSON();
//		jsonToXML();
//		xmlToJSON();
//		javaBeanToJSON();
		javaBeanToXML();
	}
	
}
package com.xxh.entity;
 
/**
 * 描述:实体
 * 
 */
public class UserInfo {
	public String username;
	public String password;
 
	public String getUsername() {
		return username;
	}
 
	public void setUsername(String username) {
		this.username = username;
	}
 
	public String getPassword() {
		return password;
	}
 
	public void setPassword(String password) {
		this.password = password;
	}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>tools</groupId>
  <artifactId>tools</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>tools Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!-- <dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>1.2.8</version>
	</dependency> -->
 
	<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
	<dependency>
	    <groupId>net.sf.json-lib</groupId>
	    <artifactId>json-lib</artifactId>
	    <version>2.4</version>
	    <classifier>jdk15</classifier>
	</dependency>
	<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
	<dependency>
	    <groupId>commons-lang</groupId>
	    <artifactId>commons-lang</artifactId>
	    <version>2.6</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
	<dependency>
	    <groupId>commons-logging</groupId>
	    <artifactId>commons-logging</artifactId>
	    <version>1.2</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
	<dependency>
	    <groupId>commons-beanutils</groupId>
	    <artifactId>commons-beanutils</artifactId>
	    <version>1.9.3</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
	<dependency>
	    <groupId>commons-collections</groupId>
	    <artifactId>commons-collections</artifactId>
	    <version>3.2.1</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
	<dependency>
	    <groupId>net.sf.ezmorph</groupId>
	    <artifactId>ezmorph</artifactId>
	    <version>1.0.6</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/xom/xom -->
	<dependency>
	    <groupId>xom</groupId>
	    <artifactId>xom</artifactId>
	    <version>1.2.5</version>
	</dependency>
	
		
  </dependencies>
  <build>
    <finalName>tools</finalName>
  </build>
</project>

JSON.parseObject(String str)与JSONObject.parseObject(String str)的区别

一、首先来说说fastjson
fastjson 是一个性能很好的 Java 语言实现的 JSON 解析器和生成器,来自阿里巴巴的工程师开发。其主要特点是:

① 快速:fastjson采用独创的算法,将parse的速度提升到极致,超过所有基于Java的json库,包括曾经号称最快的jackson;

② 强大:Fastjson完全支持http://json.org的标准(也是Google官方网站收录的参考实现之一);支持各种JDK类型;包括基本类型、JavaBean、Collection、Map、Enum、泛型等;

③零依赖:没有依赖其它任何类库除了JDK,能够直接运行在Java SE 5.0以上版本;支持Android;开源 (Apache 2.0)。

为什么要说fastjson,因为,JSON.parseObject(String str)和JSONObject.parseObject(String str)就是fastjson中的方法。

二、parseObject(String str)的作用

JSON.parseObject(String str)是将str转化为相应的JSONObject对象,其中str是“键值对”形式的json字符串,转化为JSONObject对象之后就可以使用其内置的方法,进行各种处理了。

三、JSON.parseObject(String str)与JSONObject.parseObject(String str)的区别

根据源码显示:JSON是一个抽象类,JSON中有一个静态方法parseObject(String text),将text解析为一个JSONObject对象并返回;JSONObject是一个继承自JSON的类,当调用JSONObject.parseObject(result)时,会直接调用父类的parseObject(String text)。所以两者没什么区别,一个是用父类去调用父类自己的静态的parseObject(String text),一个是用子类去调用父类的静态parseObject(String text),两者调的是同一个方法。
 

从json里拿到value

例子:

{"testsetTestcaseExecute":{"auditor":"vame","testcaseType":"Exception"}}
 JSONObject object = (JSONObject) JSONObject.parse(str);
 System.out.println(object.getJSONObject("testsetTestcaseExecute").get("auditor"));
        
 System.out.println(object.getJSONObject("testsetTestcaseExecute").get("testcaseType"));

json字符串转换为json对象

 // 将字符串转为JSON对象再解析
        JSONObject json = JSONObject.parseObject(componentRelationVo.getTaskRelation());

json对象转换为字符串

JSONObject.toJSONString(relationVo)

 1.List转JSONArray

List<T> list = new ArrayList<T>();
JSONArray array= JSONArray.parseArray(JSON.toJSONString(list));


2.JSONArray转List

JSONArray array = new JSONArray();
List<EventColAttr> list = JSONObject.parseArray(array.toJSONString(), EventColAttr.class);


3.String转JSONArray

String st = "[{name:Tim,age:25,sex:male},{name:Tom,age:28,sex:male},{name:Lily,age:15,sex:female}]";
JSONArray tableData = JSONArray.parseArray(st);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值