delphi 解析json java_Delphi处理JSON格式数据

本文介绍如何在Delphi中使用uLkJSON组件解析和构造JSON数据,以及通过HTTP POST请求发送JSON数据到JavaServlet,并处理返回的JSON响应。示例代码展示了如何创建JSON对象、发送POST请求以及解析返回的JSON结果。
摘要由CSDN通过智能技术生成

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.

*/

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

/**

* The doGet method of the servlet.

*

* 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.

*

* 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.

*

* @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/,如需转载,请注明出处,否则将追究法律责任。

DELPHI彫和JSON代码* Copyright (c) 2006,2007,2008,2009 Leonid Koninin * leon_kon@users.sourceforge.net * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Leonid Koninin ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL Leonid Koninin BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值