JAVA编码(1)——通过HTTP传输协议接口返货JSON数据

JAVA中使用JSON进行数据传递:

http://www.cnblogs.com/undead/archive/2012/07/18/2594900.html
 
返回前台数据:
private String errorMsg(){
  JSONObject jsonObject = null;
  try {
    jsonObject = new JSONObject();
    jsonObject.put("status", "2");
    jsonObject.put("respmsg", "获取WAP接口返回数据出现异常,请核查!");
  } catch (Exception e) {
    printLogInfo("异常信息返回出错,原因:"+e.getLocalizedMessage());
    e.printStackTrace();
  }
  return ajax(jsonObject.toString(), "text/html");
}
// AJAX输出,返回null
public String ajax(String content, String type) {
  try {
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType(type + ";charset=UTF-8");
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.getWriter().write(content);
    response.getWriter().flush();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return null;
}
 
 
=================================================================
 
 
package cn.com.sinosoft.test;
 
import java.util.ArrayList;
import java.util.List;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
public class TestSplit {
  private static String backMessage;
  private static JSONArray array;
  private static Listlist;
  private static int listsize;
  private static int number;
  public static void main(String[] args) throws JSONException {
    JSONArray jsonArray = new JSONArray();
    list = new ArrayList();
    backMessage = "成功";
    listsize = 606;
    //最外层的JSONObject
    JSONObject json = new JSONObject();
    json.put("respmsg", backMessage);
    json.put("listSize", listsize);
    number = 2;
    generateJSONObject(list,number);
    number = 3;
    generateJSONObject(list,number);
    for (int i = 0; i < list.size(); i++) {
      jsonArray.put(list.get(i));
    }
    json.put("fundList", jsonArray);
    System.out.println(json.toString());
}
private static void generateJSONObject(Listlist, int number) {
   //次层的JSONObject   num1
  JSONObject json = new JSONObject();
  try {
    json.put("buyCount", 32);
    JSONObject json1 = new JSONObject();
    json1.put("username", "wanglihong");
    json1.put("height", 12.5);
    json1.put("age", 24);
    json.put("fundinfo", json1);
    array = new JSONArray();
    for (int i = 0; i < number; i++) {
      //最里层的JSONObject
      JSONObject json2 = new JSONObject();
      json2.put("realname", "xushuyi");
      json2.put("sex", 1);
      json2.put("email", "1490722165@qq.com");
      array.put(json2);
    }
    json.put("fundChagRateList", array);
    list.add(json);
  } catch (Exception e) {
    e.printStackTrace();
  }
}
}
 

  

posted @ 2015-04-05 18:46  xu_shuyi  阅读(175)  评论(0)    收藏  举报