Servlet接收application/json和application/xml请求体

环境

jdk7
json-lib-2.4.jar

代码


import net.sf.json.JSON;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
    String line = null;
    StringBuilder str = new StringBuilder();
    while ((line = br.readLine()) != null) {
      str.append(line);
    }
    if(isJson(str.toString())){
      // 这是一个json格式字符串
      //TODO 业务逻辑
    }
    if(isXML(str.toString())){
      // 这是一个xml格式字符串
      //TODO 业务逻辑
    }
}

public static boolean isJson(String value) {
    try {
      JSONObject.fromObject(value);
    } catch (JSONException e) {
      return false;
    }
    return true;
  }


  public static boolean isXML(String value) {
    try {
      DocumentHelper.parseText(value);
    } catch (DocumentException e) {
      return false;
    }
    return true;
  }

其他

//xml转JSON
  public static String xmlToJson(String str) {
    XMLSerializer xmlSerializer = new XMLSerializer();
    JSON json = xmlSerializer.read(str);
    return json.toString();
  }
//json转XML
  public static String jsonToXml(String json){
    JSONObject jobj = JSONObject.fromObject(json);
    String xml =  new XMLSerializer().write(jobj);
    return xml;
  }

你可能感兴趣的:(java,servlet)