Delphi處理JSON格式資料

gdutllf2006發表於2017-02-14
1 下載/安裝元件uLkJSON.pas
2 下載/安裝元件strprocess.pas


uses SuperObject,uLkJSON,strprocess;
//POST JSON資料格式的請求


procedure TForm1.btnPostRequestClick(Sender: TObject);
var
  Url,strBandID,strShopID,str3,str4,strCoin: string;//請求地址
  strReqJson: TStringStream;
  JsonReceived,JsonSend:  TlkJSONobject;
  strResp : string;
begin
 //請求地址
  Url := '';
  //請求引數{"bandid":"手環ID","shopid":"場地ID","sign":"引數簽名"}
  //建立一個包含JSON資料的變數,這種格式有問題嗎?


   strBandID  := '000001';
   strShopID  := '000001';


   JsonSend := TlkJSONobject.Create;//必須先Create一個物件
   JsonSend.Add('bandid',strBandID);
   JsonSend.Add('shopid',strShopID);
   JsonSend.Add('sign',getSignature(strBandID+strShopID));


    strReqJson := TStringStream.Create(TlkJSON.GenerateText(JsonSend));
    memo1.Lines.Clear;
    memo1.Lines.add(strReqJson.DataString);
    strReqJson.Position := 0;
  try
    IdHTTP1.Request.ContentType := 'application/json';
    strResp := IdHTTP1.Post(URL, strReqJson);
    memo2.Lines.Clear;
    Memo2.Lines.Text :=strResp;
  // 錯誤的JSON資料格式,為什麼會多了[] : [{"code":"0","message":"success","object":{"bandid":"000001","coin":"5"}}]
  // 返回正確的JSON資料格式 {"code":"0","message":"success","object":{"bandid":"000001","coin":"5"}}
    
    JsonReceived := TlkJSON.ParseText(TrimRightChar(TrimLeftChar(trim(strResp),'['),']')) as TlkJSONobject;
    //Jstart.field 為jbase時,
    strBandID := vartostr(JsonReceived.Field['object'].Field['bandid'].Value);
    memo3.Lines.Clear;
    memo3.Lines.add(strBandID);
    //Jstart.field 有子資料為jslist時
    strCoin := vartostr(JsonReceived.Field['object'].Field['coin'].Value);
    memo3.Lines.add(strCoin);


             
  finally
    JsonSend.Free;
    JsonReceived.Free;
  end;
end;






檔案ServletDelphi.java


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


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




public class ServletDelphi extends HttpServlet {


/**
* Constructor of the object.
*/
public ServletDelphi() {
super();
}


/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}


/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.

* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


response.getWriter().println("Hello Servlet Delphi!");
}


/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.

* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


String strJson = inputStream2String(request.getInputStream());
//System.out.println("receive json:"+json);
//response.getWriter().println(json);


JSONObject subJsonObj = new JSONObject();
subJsonObj.put("bandid", "000001");
subJsonObj.put("coin", "5");

JSONObject responseJsonObj = new JSONObject();
responseJsonObj.put("code", "0");
responseJsonObj.put("message", "success");
responseJsonObj.put("object", subJsonObj);


JSONArray array = new JSONArray();
array.add(responseJsonObj);
//System.out.println("return JSON: " + array.toString());
response.getWriter().println(array.toString());
       

}


/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}


public static String inputStream2String (InputStream in) throws IOException { 
StringBuffer out = new StringBuffer(); 
byte[] b = new byte[4096]; 
for (int n; (n = in.read(b)) != -1;) { 
out.append(new String(b, 0, n)); 

return out.toString(); 
}


}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10248702/viewspace-2133540/,如需轉載,請註明出處,否則將追究法律責任。

相關文章