Java MessageFormat.format 特殊符号、单引号

本文介绍了如何利用MessageFormat.format方法来组装特定格式的JSON字符串。通过实例演示了如何正确处理字符串中的特殊字符如单引号及大括号,确保最终生成的JSON字符串符合预期格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在MessageFormat.format方法中组装jason数据字符串:{code:"w1",des:"w2"},起止分别有左大括号和右大括号。

方法是将单引号把大括号包含起来。如下:

        String responseTemplate = "'{'code:\"{0}\",des:\"{1}\"'}'";

        System.out.println(MessageFormat.format(responseTemplate, "w1","w2"));

如果格式化字符串中包含单引号,处理方法是用2个单引号进行转义

        String responseTemplate = "'{'code:''{0}'',des:''{1}'''}'";
        System.out.println(MessageFormat.format(responseTemplate, "w1","w2"));

处理结果:{code:'w1',des:'w2'}

String threadName = Thread.currentThread().getName(); // logger.info(MessageFormat.format("{0} - 正在...请求{1}/{2}接口: param = {3}",threadName,module,action,paramters)); String url = String.format("%s/%s/%s", API_DOMAIN, module, action); PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); URLConnection connection = realUrl.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); String tick = getcurrentTick(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.addRequestProperty("ox_appkey", APP_KEY); connection.addRequestProperty("ox_tick", tick); connection.addRequestProperty("ox_version", "1.0"); connection.addRequestProperty("ox_token", createToken(paramters, tick)); logger.debug("请求接口paramters: " + URLEncoder.encode(paramters, "UTF-8")); logger.debug("请求接口ox_token: " + createToken(paramters, tick)); logger.debug("请求接口ox_tick: " + tick); logger.debug("请求接口ox_appkey: " + APP_KEY); out = new PrintWriter(connection.getOutputStream()); out.print("data=" + URLEncoder.encode(paramters, "UTF-8")); out.flush(); in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { logger.error("发送 POST 请求出现异常!" + e); throw e; } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } 转为curl
最新发布
07-09
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值