【转载】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 = "123456宋发元";
        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引入资源

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  4.0.0
  tools
  tools
  war
  0.0.1-SNAPSHOT
  tools Maven Webapp
  http://maven.apache.org
 
   
      junit
      junit
      3.8.1
      test
   

    
   
 
    
    
        net.sf.json-lib
        json-lib
        2.4
        jdk15
    

    
    
        commons-lang
        commons-lang
        2.6
    

    
    
        commons-logging
        commons-logging
        1.2
    

    
    
        commons-beanutils
        commons-beanutils
        1.9.3
    

    
    
        commons-collections
        commons-collections
        3.2.1
    

    
    
    
        net.sf.ezmorph
        ezmorph
        1.0.6
    

    
    
        xom
        xom
        1.2.5
    

    
        
 

 
    tools
 

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

 

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

你可能感兴趣的:(【转载】JSONObject使用方法详解)