暑期项目经验(六)--struts+json

              struts+json

tips:注意 struts.xml配置,  json-default  及引入 struts2-json-plugin-2.1.8.1.jar 包

 

1、json基础知识

 JSON(JavaScript Object Notation)是一种轻量级的数据格式,采用完全独立于语言的文本格式,是理想的数据交换格式。同时,JSON是Javascript原生格式,这意 味着在javascript中处理JSON数据不需要任何特殊的API或工具包,而且效率非常高。

     JSON的结构如下:

  • “名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
  • 值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)

      一个标准的json格式:

{"name":"jifeng","company":"taobao"}

 

2.json的解析

json的解析方法共有两种:1. eval() ; 2.JSON.parse() ; 3.evalJSON()。具体使用方法如下:

var jsonstr = ‘{"name":"jifeng","company":"taobao"}‘;
//eval function
var evalJson = eval(‘(‘ + jsonstr + ‘)‘);
// JSON.parse function
var JSONParseJson = JSON.parse(jsonstr);

//这个引入property.js
var obj = jsonstr.evalJSON();

 

3.struts2的json响应的param类型   param name=" XX "

root:只包含xx对象excludeProperties  :除了xx之外的集合includeProperties : 包含xx的集合
wrapPrefix :json结果开头添加xx(比如<paramname="wrapPrefix">[</param>)
wrapSuffix :同上,只不过是结尾
ignoreHierarchy :转化时是否忽略继承关系true/false
enumAsBean : 是否将枚举当做一个bean处理
enableGZIP :是否支持gzip压缩输出
noCache :是否缓存
excludeNullProperties : 是否转化输出 null值
statusCode :设置响应代号比如 304
callbackParameter : JSONP跨域访问的回调设置
contentType : 输出类型

 

4.fastjson  实例

实体类:

package com.pxj.fastjson.entity;

public class Student {
     private int id;  
        private String name;  
        private int age;  
          
        /** 
         * 默认的构造方法必须不能省,不然不能解析 
         */  
          
        public Student(){  
              
        }  
        public Student(int id,String name,int age) {  
            this.id = id;  
            this.name = name;  
            this.age = 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;  
        }  
          
        @Override  
        public String toString() {  
            return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";  
        }  
}

 

package com.pxj.fastjson.entity;

import java.util.List;

public class Teacher {
    private int id;  
    private String name;  
      
    private List<Student> students;  
      
  
    /** 
     * 默认的构造方法必须不能省,不然不能解析 
     */  
    public Teacher() {  
          
    }  
    public Teacher(int id,String name) {  
        this.id = id;  
        this.name = name;  
    }  
      
    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 List<Student> getStudents() {  
        return students;  
    }  
    public void setStudents(List<Student> students) {  
        this.students = students;  
    }  
    @Override  
    public String toString() {  
        return "Teacher [id=" + id + ", name=" + name + ", mStudents="  
                + students + "]";  
    }  
}

 

 测试类:

package com.pxj.fastjson.demo;

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

import org.junit.Test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.pxj.fastjson.entity.Student;
import com.pxj.fastjson.entity.Teacher;

public class Demo {
    @Test
    public void test1() {
        Student student = new Student(0, "Aaron", 24);
        System.out.println(JSON.toJSONString(student));
    }
    //{"age":24,"id":0,"name":"Aaron"}

    @Test
    public void test2() {
        List<Student> students = new ArrayList<Student>();
        for (int i = 0; i < 5; i++) {
            Student stu = new Student(i, "Student" + i, 18 + i);
            students.add(stu);
        }
        System.out.println(JSON.toJSONString(students));
    }

    @Test
    public void test3() {
        List<Teacher> teaList = new ArrayList<Teacher>();
        for (int i = 0; i < 10; i++) {
            Teacher teacher = new Teacher(i, "Teacher " + i);
            List<Student> stus = new ArrayList<Student>();
            for (int j = 0; j < 4; j++) {
                Student s = new Student(j, "Student" + j, 18 + j);
                stus.add(s);
            }
            teacher.setStudents(stus);
            teaList.add(teacher);
        }
        String jsonTeach = JSON.toJSONString(teaList);
        System.out.println("fastjson = " + jsonTeach);
    }

    // 按照标准的json 格式输出
    @Test
    public void test4() {
        Student student = new Student(0, "Aaron", 24);
        System.out.println(JSON.toJSONString(student, true));
    }

    // 实体类中的某个字段或某几个不进行解析呢
    @Test
    public void test5() {
        List<Student> students = new ArrayList<Student>();
        for (int i = 0; i < 5; i++) {
            Student stu = new Student(i, "Student" + i, 18 + i);
            students.add(stu);
        }
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Student.class, "id", "age");
        String jsonStu = JSON.toJSONString(students, filter);
        System.out.println(jsonStu);
    }
    //反序列化主要使用的是JSON.parseObject(str,class); 它就能把我们的str 转化为class 类型的对象,当然还有更复杂的对象
    @Test
    public void test6() {
        List<Student> students = new ArrayList<Student>();
        for (int i = 0; i < 5; i++) {
            Student stu = new Student(i, "Student" + i, 18 + i);
            students.add(stu);
        }
        String jsonStu = JSON.toJSONString(students);
        List<Student> stu =JSON.parseObject(jsonStu, new TypeReference<List<Student>>(){});  
        for(int i=0;i<stu.size();i++)   
        {  
            System.out.println(stu.get(i));  
        }  
    }
}

 

 5. struts+json实例

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <base href="<%=basePath%>">
        <title>获取</title>
        <script type="text/javascript" src="js/jquery-1.4.3.js">
</script>
        <script type="text/javascript">
function loadInfo() {
    $("#info").load("loadInfo");
}
</script>
    </head>
    <body>
        <input type="button" value="获取" id="btnGet" onclick="loadInfo()" />
        <div id="info"></div>
    </body>
</html>

 

 comment.java

package com.pxj.entity;

public class Comment {
    private long id;
    private String nickname;
    private String content;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }   
}

 InfoAction.java

package com.pxj.action;

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

import org.apache.struts2.json.annotations.JSON;

import com.pxj.entity.Comment;

public class InfoAction {
    private static final long serialVersionUID = 1359090410097337654L;

    private List<Comment> comments = new ArrayList<Comment>();
    //没getter and setter方法的属性不会被串行化到JSON
    @SuppressWarnings("unused")
    private String title;
    //!!!使用transient修饰的属性也会被串行化到JSON
    private transient String content;

    public String loadInfo() {
        title="123木头人";
        content="你是木头人,哈哈。";
        loadComments();
        return "success";
    }

    /**
     * 加载留言信息
     */
    private void loadComments() {
        Comment com1 = new Comment();
        com1.setContent("很不错嘛");
        com1.setId(1);
        com1.setNickname("纳尼");
        Comment com2 = new Comment();
        com2.setContent("哟西哟西");
        com2.setId(2);
        com2.setNickname("小强");
        comments.add(com1);
        comments.add(com2);
    }
    //为了使content对象不被串行化到JSON,在不能舍弃其getter setter方法的时候,我们可以这样在content的getter方法上面加上注解:@JSON(serialize=false)
    @JSON(serialize=false)
    public List<Comment> getComments() {
        return comments;
    }

    public void setComments(List<Comment> comments) {
        this.comments = comments;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

 struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <package name="default" namespace="/" extends="json-default">
    
        <action name="loadInfo" class="com.pxj.action.InfoAction" method="loadInfo">
            <result name="success" type="json"></result>
        </action>
</struts>

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。