java 后台返回json数据给前台

第一步:新建一个JsonBinder.java类,代码如下:

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.util.StringUtils;

public class JsonBinder {
 private static Logger logger = LogManager.getLogger(JsonBinder.class);

 private ObjectMapper mapper;

 @SuppressWarnings("deprecation")
 private JsonBinder( JsonSerialize.Inclusion inclusion) {
  mapper = new ObjectMapper();   
  
  //设置输出包含的属性
  mapper.getSerializationConfig().setSerializationInclusion(inclusion);
    
  //设置输入时忽略JSON字符串中存在而Java对象实际没有的属性
  mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
 }
 public JsonBinder(){
  
 }

 /**
  * 创建输出全部属性到Json字符串的Binder.
  */
 public static JsonBinder buildNormalBinder() {
  return new JsonBinder(JsonSerialize.Inclusion.ALWAYS);
 }

 /**
  * 创建只输出非空属性到Json字符串的Binder.
  */
 public static JsonBinder buildNonNullBinder() {
  return new JsonBinder(JsonSerialize.Inclusion.NON_NULL);
 }

 /**
  * 创建只输出初始值被改变的属性到Json字符串的Binder.
  */
 public static JsonBinder buildNonDefaultBinder() {
  return new JsonBinder(JsonSerialize.Inclusion.NON_DEFAULT);
 }
 
 /**
  * 创建只输出初始值被改变的属性到Json字符串的Binder.
  */
 public static JsonBinder buildNonEmptyBinder() {
  return new JsonBinder(JsonSerialize.Inclusion.NON_EMPTY);
 }
 
 /**
  * 如果JSON字符串为Null或"null"字符串,返回Null.
  * 如果JSON字符串为"[]",返回空集合.
  *
  * 如需读取集合如List/Map,且不是List<String>这种简单类型时使用如下语句:
  * List<MyBean> beanList = binder.getMapper().readValue(listString, new TypeReference<List<MyBean>>() {});
  */
 public <T> T fromJson(String jsonString, Class<T> clazz) {
  try {
   return mapper.readValue(jsonString, clazz);
  } catch (IOException e) {
   logger.warn("parse json string error:" + jsonString, e);
   return null;
  }
 }
 

 /**
  * 如果对象为Null,返回"null".
  * 如果集合为空集合,返回"[]".
  */
 public String toJson(Object object) {

  try {
   return mapper.writeValueAsString(object);
  } catch (IOException e) {
   logger.warn("write to json string error:" + object, e);
   return null;
  }
 }

 /**
  * 设置转换日期类型的format pattern,如果不设置默认打印Timestamp毫秒数.
  */
 public void setDateFormat(String pattern) {
  if (StringUtils.hasText(pattern)) {
   DateFormat df = new SimpleDateFormat(pattern);
   mapper.getSerializationConfig().withDateFormat(df);
   mapper.getDeserializationConfig().withDateFormat(df);
  }
 }

 /**
  * 取出Mapper做进一步的设置或使用其他序列化API.
  */
 public ObjectMapper getMapper() {
  return mapper;
 }
 /**
  * 字符转换MAP
  * @param line
  * @return
  */
 public Map<String ,Object> stringMap(String line){
  String lineString=line.replace("{", "");
  String linString=lineString.replace("}","");
  Map<String ,Object> retMap=new HashMap<String, Object>();
  String [] lineStrings=linString.split(",");
  for (int i = 0; i < lineStrings.length; i++) {
   String lenString=lineStrings[i].trim();
   String lidd[]=lenString.split("=");
   retMap.put(lidd[0].trim(),lidd[1].trim());
  }
  return retMap;
 }
 
}

第二步:新建一个JsonReturnModel.java类,代码如下:

import java.io.Serializable;

public class JsonReturnModel implements Serializable {
 private static final long serialVersionUID = -6705263054881844917L;
 private boolean success;// 是否成功
 private int code;
 private String msg; // 返回消息

 public int getCode() {
  return code;
 }

 public void setCode(int code) {
  this.code = code;
 }

 public JsonReturnModel() {
 }
 
 public JsonReturnModel(boolean success, int code, String msg) {
  this.success = success;
  this.code = code;
  this.msg = msg;
 }

 public JsonReturnModel(boolean success, String msg) {
  this.success = success;
  this.msg = msg;
 }

 public boolean getSuccess() {
  return success;
 }

 public void setSuccess(boolean success) {
  this.success = success;
 }

 public String getMsg() {
  return msg;
 }

 public void setMsg(String msg) {
  this.msg = msg;
 }
}

 

第三步:测试

import java.io.UnsupportedEncodingException;
import com.sqzw.sms.util.JsonBinder;
import com.sqzw.sms.util.JsonReturnModel;
public class Test {
 public static void main(String[] args) throws UnsupportedEncodingException {
    JsonReturnModel jm=new JsonReturnModel(true,0,"连接服务器成功");
    JsonBinder jsonbinder=JsonBinder.buildNonNullBinder();
  String result=jsonbinder.toJson(jm);
  System.out.println(result);
    }
}
运行结果如下:

{"success":true,"code":0,"msg":"连接服务器成功"}

第四步:新建一个SmsSendMessageAction.java类 继承ActionSupport,代码如下:import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sqzw.sms.util.Common;
import com.sqzw.sms.util.JsonReturnModel;
public class SmsSendMessageAction extends ActionSupport{
 private static final long serialVersionUID = 1087655523102850222L;
 private Logger logger=LogManager.getLogger(SmsSendMessageAction.class);
 private HttpServletResponse response = null; 
 /**
  * @method:checkService
  * @desc 验证连接服务器是否成功
  * @since 2012-07-16
  * @author fx
  */
 public void checkService(){
  response=ServletActionContext.getResponse();
  response.setCharacterEncoding("utf-8");
  try{
   response.getWriter().print(Common.returnJsonResult(new JsonReturnModel(true,0,"连接服务器成功")));
   return;
   
  }catch(Exception ex){
   try {
    response.getWriter().print(Common.returnJsonResult(new JsonReturnModel(false,-1,"连接服务器失败")));
   } catch (IOException e) {
    // TODO Auto-generated catch block
    logger.error("连接服务器失败::"+e.getMessage());
   }
   logger.error("连接服务器失败::"+ex.getMessage());
   
  }finally{
   try {
    response.getWriter().close();
   } catch (Exception e) {
    logger.error("SmsSendMessageAction类中的|checkService()关闭IO流出错::"+e.getMessage());
    
   }
  }
 }
}

运行结果如下:

http://localhost:8080/sms/checkServiceAction.action

java 后台返回json数据给前台_第1张图片

你可能感兴趣的:(java,json,exception,String,object,服务器)