JSON的简单运用

来源:互联网 发布:vmware mac os 慢 编辑:程序博客网 时间:2024/05/18 03:25
1.Json
   What:特殊的字符串
2.对象和Json之间的转换
    <1>对象--->字符串:  JsonObject jsonObject=JsonObject.fromObject(对象);
    <2>字符串-->对象:  
        ①.JsonObject jsonObject=JsonObject.fromObject(字符串);

        ②.对象=jsonObject.toBean(jsonObject,对象.class);

3.对象集合和字符串之间的转换
    <1>对象集合--->字符串
            JsonArray jsonArray=JsonArray.fromObject(对象集合);
    <2>字符串---->对象集合
            JsonArray jsonArray=JsonArray.fromObject(字符串);
            对象集合=jsonArray.toCollection(jsonArray);
4.在JSP中使用Json
    在jsp页面引入json.js文件
   <1>Json.stringify(对象)----->将JS对象转换成Json字符串
   <2>Json.parse-------->将Json字符串转成Js对象

http://www.bejson.com/  校验Json格式


测试代码:

package com.zking.test;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.junit.Test;
/**
 * {} Json对象          JsonObject
 * [] Json对象集合   JsonArray
 */
import com.zking.entity.Person;

public class TestJson {
    
    /**
     * 将Json转成对象集合
     */
    @Test
    public void testJsonToArray(){
        List<Person> persons=new ArrayList<Person>();
        for (int i = 1; i <=36; i++) {
            persons.add(new Person(i, "G160628S"+i, 18));
        }
        JSONArray jsonArray=JSONArray.fromObject(persons);
        
        List<Person> persons2=(List<Person>) JSONArray.toCollection(jsonArray, Person.class);
        for (Person person : persons2) {
            System.out.println(person);
        }
        
    }
    
    
    
    
    /**
     * 对象集合转成Json(常用)
     */
    @Test
    public void testArrayToJson(){
        List<Person> persons=new ArrayList<Person>();
        for (int i = 1; i <=36; i++) {
            persons.add(new Person(i, "G160628S"+i, 18));
        }
        
        JSONArray jsonArray=JSONArray.fromObject(persons);
        System.out.println(jsonArray.toString());
    }
    
    /**
     * json字符串转成对象
     */
    @Test
    public void testJsonToObject(){
        Person person=new Person(1, "亮亮", 17);
        JSONObject jsonObject=JSONObject.fromObject(person);
        String s=jsonObject.toString();
        
        Person person2=(Person) JSONObject.toBean(jsonObject, Person.class);
        System.out.println(person2);
    }
    
    /**
     * 对象转成Json(常用)
     */
    @Test
    public void testObjectToJson(){
        Person person=new Person(1, "亮亮", 17);
        JSONObject jsonObject=JSONObject.fromObject(person);
        System.out.println(jsonObject.toString());
        
    }
}