【转载】JSONObject使用方法详解

地址:https://blog.csdn.net/u011019141/article/details/76579019

/**
 * 项目名称:tools
 * 项目包名:com.songfayuantools.json
 * 创建时间:2017年7月31日上午11:58:51
 * 创建者:Administrator-宋发元
 * 创建地点:
 */
package com.songfayuantools.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互相转换的包。
 * @author songfayuan
 * 2017年7月31日上午11:58:51
 */
public class Json {
 
    /**
     * 描述:json字符串转java代码
     * @author songfayuan
     * 2017年8月2日下午2:24:47
     */
    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字符串
     * @author songfayuan
     * 2017年8月2日下午2:30:58
     */
    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字符串
     * @author songfayuan
     * 2017年8月2日下午2:56:30
     */
    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字符串
     * @author songfayuan
     * 2017年8月2日下午3:19:25
     */
    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字符串
     * @author songfayuan
     * 2017年8月2日下午3:39:10
     */
    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字符串
     * @author songfayuan
     * 2017年8月2日下午3:48:08
     */
    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();
    }
    
}
实体

/**
 * 项目名称:tools
 * 项目包名:com.songfayuantools.entity
 * 创建时间:2017年8月2日下午3:34:46
 * 创建者:Administrator-宋发元
 * 创建地点:
 */
package com.songfayuantools.entity;
 
/**
 * 描述:实体
 * 
 * @author songfayuan 2017年8月2日下午3:34:46
 */
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;
    }
}
maven引入资源

<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>

==========================================

JSONObject jo = JSONObject.fromObject(map);
常见的java代码转换成json

--请注意,这个方法在对Object转换的时候是按照domain类中的所有getXXX()方法进行转换的。如果你在类中写了非属性的getXXX()方法,那么返回给你的就会有XXX属性了。

--使用net.sf.json.*下的类(jar包是json-lib-x.x.jar)

1. List集合转换成json代码

List list = new ArrayList();

list.add( "first" );

list.add( "second" );

JSONArray jsonArray2 = JSONArray.fromObject( list );

2. Map集合转换成json代码

Map map = new HashMap();

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 json = JSONObject.fromObject(map);

3. Bean转换成json代码

JSONObject jsonObject = JSONObject.fromObject(new JsonBean());

4. 数组转换成json代码

boolean[] boolArray = new boolean[] { true, false, true };

JSONArray jsonArray1 = JSONArray.fromObject(boolArray);

5. 一般数据转换成json代码

JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );

================================================================================

public static void main(String[] args) {
  Map map=new HashMap();
  map.put("我","妹");
  map.put("擦","哇");
  map.put("你","呀");
  JSONObject json = JSONObject.fromObject(map);
  System.out.println(json);
 }

輸出的結果 {"我":"妹","擦":"哇","你":"呀"}

toBean();

首先一个javabean对象
public class Student {

    private int id ;
    private String name;
    private int age;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    public String toString(){
        return this.id + ", " + this.name + ", " + this.age;
    }
}

然后测试toBean方法的类
import net.sf.json.JSONObject;

public class ToBeanTest {

    public static void main(String[] args) {
        
        String json = "{id:'1001',name:'张三',age:'22'}";
        Student stu = new Student();
        JSONObject obj = JSONObject.fromObject(json);
        stu = (Student)JSONObject.toBean(obj, Student.class);
        System.out.println(stu);
    }

}
输出结果为1001, 张三, 22 
然后我们在修改修改
import net.sf.json.JSONObject;

public class ToBeanTest {

    public static void main(String[] args) {
        
        String json = "{id:'1001',name:'张三'}";
        Student stu = new Student();
        JSONObject obj = JSONObject.fromObject(json);
        stu = (Student)JSONObject.toBean(obj, Student.class);
        System.out.println(stu);
    }

}
把年龄给去掉age为int型,输出结果为:1001, 张三, 0 
然后再做小小改动
import net.sf.json.JSONObject;

public class ToBeanTest {

    public static void main(String[] args) {
        
        String json = "{id:'1001',age:'22'}"; 
        Student stu = new Student();
        JSONObject obj = JSONObject.fromObject(json);
        stu = (Student)JSONObject.toBean(obj, Student.class);
        System.out.println(stu);
    }

}
把姓名给去掉name为String型,输出结果为:1001, null, 22 
再改动一下:
import net.sf.json.JSONObject;

public class ToBeanTest {

    public static void main(String[] args) {
        
        String json = "{id:'1001',name:'张三',age:'nn'}";
        Student stu = new Student();
        JSONObject obj = JSONObject.fromObject(json);
        stu = (Student)JSONObject.toBean(obj, Student.class);
        System.out.println(stu);
    }

}
把age改成非整形,输出结果为:
1001, 张三, 0 

再改动一下:
import net.sf.json.JSONObject;

public class ToBeanTest {

    public static void main(String[] args) {
        
        String json = "{id:'1001',name:'张三',age:'22',sex:'男'}";
        Student stu = new Student();
        JSONObject obj = JSONObject.fromObject(json);
        stu = (Student)JSONObject.toBean(obj, Student.class);
        System.out.println(stu);
    }

}
加了一个sex:'男'的一对键值,输出结果为:
1001, 张三, 22

猜你喜欢

转载自blog.csdn.net/beidaol/article/details/83748512