Java中Map,JSONobject,list,JSONArray,String间的转换与在http请求中inputstream流与 Byte与String间的转换。

Java对象与JSON转换及HTTP流处理
本文介绍了Java中Map、JSONObject、JSONArray、List和String之间的相互转换,包括使用Fastjson库进行转换的示例。同时,讲解了在HTTP请求中InputStream流与Byte和String的转换方法,提供了一段读取InputStream到Byte数组以及Byte数组转String的代码片段。

 

目录

 Java中Map,JSONobject,list,JSONArray,String间的转换

 Map,list ,JSONArray ,转为JSON格式的String形式,通用转换

 JSON格式的String形式转任何类型(如Map ,list,JsonArray),通用转换

 在http请求中inputstream流与 Byte与String间的转换。

inputstram转byte[]

byte[]转string


 Java中Map,JSONobject,list,JSONArray,String间的转换

首先在maven工程中添加依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>

从数据库中获取数据一般我使用万能Map ,即数据库的返回值类型是 List<hashmap<String,object>>

 Map,list ,JSONArray ,转为JSON格式的String形式,通用转换

JSON.toJSONString(object object)

 JSON格式的String形式转任何类型(如Map ,list,JsonArray),通用转换

JSON.parseObject(string s,object.class)

有了这两个通用的转换就能实现list<->JSONArray,map<->JSONObject 间的转换

同时ali的fastjson还提供了其他的方法(如string 转jsonArray)

string 转json数组(JSONArray)

  JSONArray jsonArray =JSONArray.parseArray(s);

 在http请求中inputstream流与 Byte与String间的转换。

inputstram转byte[]

 public static byte[] read(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = inStream.read(buffer)) != -1)
        {
            outStream.write(buffer,0,len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

byte[]转string

   byte temp[]=read(in);
   s=new String(temp,"UTF-8");

package com.httpclient.iat; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.httpclient.config.ConfigLoader; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * @Author htxu4 * @Date 2021/9/29 */ public class IatDemo8kOffline { private static ConfigLoader config = ConfigLoader.getInstance(); private static String audiopath; private static String appid; private static String auf; private static String iatUrl; private static String iatextend_params; private static int count; private static int thread; private static String svc; // 在 static 块中初始化配置 static { audiopath = config.getAudioPath("8kOffline"); appid = config.getAppId("8kOffline"); auf = config.getAuf("8kOffline"); iatUrl = config.getIatUrl("8kOffline"); iatextend_params = config.getExtendParams("8kOffline"); count = config.getTestCount("8kOffline"); thread = config.getThreadCount("8kOffline"); svc = config.getSvc("8kOffline"); } private static int num = 1; //序号 private static int filesize = 1; //总文性数 private static HashMap<String, ArrayList<byte[]>> audio_map = new HashMap<>(); private static String scookie = ""; public static void main(String[] args) { try { ArrayList<String> fileNames = readFileOnLine(audiopath); if (fileNames.size() == 0) { System.out.println("files is null"); return; } filesize = fileNames.size(); for (int i = 0; i < fileNames.size(); i++) { String fileName = fileNames.get(i); // 音频路径,此时使用相对路径,可根据实际情况自己修改 readFile(fileName); } ExecutorService executor = Executors.newFixedThreadPool(thread); for (int i = 0; i < count; i++) { executor.execute(new Runnable() { @Override public void run() { startIat(fileNames.get(getnum())); } }); } executor.shutdown(); executor.awaitTermination(99999999, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Test over."); } public static IatInfo startIat(String file) { StringBuffer allResult = new StringBuffer(); IatInfo audioInfo = new IatInfo(); audioInfo.setAuthId(getUUID()); audioInfo.setSuccess(false); audioInfo = SessionBegin(audioInfo, iatUrl, iatextend_params); if (null == audioInfo.getSid()) { return audioInfo; } audioInfo = AudioWrite(file, audioInfo, iatUrl, iatextend_params); if (audioInfo.getResultFlag()) { audioInfo = GetResult(audioInfo, iatUrl, iatextend_params); } if (null != audioInfo.getResultAudioWrite()) { allResult.append(audioInfo.getResultAudioWrite()); } if (null != audioInfo.getResultGetResult()) { allResult.append(audioInfo.getResultGetResult()); } SessionEnd(audioInfo, iatUrl, iatextend_params); if (null != allResult && allResult.length() > 0) { System.out.println("识别结果:" + allResult); audioInfo.setSuccess(true); audioInfo.setAllResult(allResult); return audioInfo; } return audioInfo; } /** * SessionBegin */ public static IatInfo SessionBegin(IatInfo audioInfo, String url, String extendParams) { audioInfo.setSuccess(false); int syncid = 0; String sid = ""; try { final Base64.Decoder decoder = Base64.getDecoder(); JSONObject json_params = new JSONObject(); json_params.put("appid", appid); json_params.put("aue", "raw"); json_params.put("auf", auf); json_params.put("cmd", "ssb"); json_params.put("extend_params", extendParams); json_params.put("svc", svc); json_params.put("auth_id", audioInfo.getAuthId()); json_params.put("syncid", String.valueOf(syncid)); syncid = syncid + 1; JSONObject json_body = new JSONObject(); json_body.put("jsonrpc", "2.0"); json_body.put("method", "deal_request"); json_body.put("params", json_params); json_body.put("id", 1); System.out.println("识别开启会话请求报文:" + json_body.toJSONString()); String responseBody = sendJsonHttpPost(url, json_body.toJSONString()); String StrResponseBody = new String(decoder.decode(responseBody), "UTF-8"); System.out.println("识别开启会话请求响应:" + StrResponseBody); JSONObject json = JSONObject.parseObject(StrResponseBody); if (json.getJSONObject("result").getInteger("ret") != 0) { System.out.println("识别开启会话报错:" + StrResponseBody); } sid = json.getJSONObject("result").getString("sid"); System.out.println("sid:" + sid); } catch (Exception e) { System.out.println("语音识别开启会话报错:" + e); } audioInfo.setSid(sid); audioInfo.setSyncid(syncid); return audioInfo; } /** * AudioWrite */ public static IatInfo AudioWrite(String path, IatInfo audioInfo, String url, String extendParams) { StringBuffer allResult = new StringBuffer(); int syncid = audioInfo.getSyncid(); try { final Base64.Decoder decoder = Base64.getDecoder(); final Base64.Encoder encoder = Base64.getEncoder(); // 音频路径,此时使用相对路径,可根据实际情况自己修改 ArrayList<byte[]> buffers = audio_map.get(path); for (int i = 0; i < buffers.size(); i++) { byte[] wave = buffers.get(i); // 音频缓存区位置信息 int audioStatus; if (i == 0) { // 第一段音频 audioStatus = 1; } else if (i == buffers.size() - 1) { // 最后一段音频 audioStatus = 4; } else { // 中音频 audioStatus = 2; } JSONObject json_params = new JSONObject(); json_params.put("appid", appid); json_params.put("audioStatus", String.valueOf(audioStatus)); json_params.put("cmd", "auw"); json_params.put("data", encoder.encodeToString(wave)); json_params.put("extend_params", extendParams); json_params.put("sid", audioInfo.getSid()); json_params.put("auth_id", audioInfo.getAuthId()); json_params.put("svc", svc); json_params.put("syncid", String.valueOf(syncid)); syncid = syncid + 1; JSONObject json_body = new JSONObject(); json_body.put("jsonrpc", "2.0"); json_body.put("method", "deal_request"); json_body.put("params", json_params); json_body.put("id", 2); System.out.println("识别写入音频请求报文:" + json_body.toJSONString()); String responseBody = sendJsonHttpPost(url, json_body.toJSONString()); String StrResponseBody = new String(decoder.decode(responseBody), "UTF-8"); System.out.println("识别写入音频请求响应:" + StrResponseBody); JSONObject json = JSONObject.parseObject(StrResponseBody); if (json.getJSONObject("result").getInteger("ret") != 0) { System.out.println("识别写入音频报错:{}" + StrResponseBody); break; } if (5 == json.getJSONObject("result").getInteger("recStatus")) { audioInfo.setResultFlag(false); audioInfo.setSuccess(true); break; } } } catch (Exception e) { audioInfo.setResultFlag(false); System.out.println("语音识别写入音频报错:" + e); } audioInfo.setSyncid(syncid); audioInfo.setResultAudioWrite(allResult); return audioInfo; } /** * GetResult */ public static IatInfo GetResult(IatInfo audioInfo, String url, String extendParams) { StringBuffer allResult = new StringBuffer(); int syncid = audioInfo.getSyncid(); try { final Base64.Decoder decoder = Base64.getDecoder(); while (true) { JSONObject json_params = new JSONObject(); json_params.put("appid", appid); json_params.put("cmd", "grs"); json_params.put("extend_params", extendParams); json_params.put("sid", audioInfo.getSid()); json_params.put("svc", svc); json_params.put("auth_id", audioInfo.getAuthId()); json_params.put("syncid", String.valueOf(syncid)); syncid = syncid + 1; JSONObject json_body = new JSONObject(); json_body.put("jsonrpc", "2.0"); json_body.put("method", "deal_request"); json_body.put("params", json_params); json_body.put("id", 3); System.out.println("识别获取结果请求报文:" + json_body.toJSONString()); String responseBody = sendJsonHttpPost(url, json_body.toJSONString()); String StrResponseBody = new String(decoder.decode(responseBody), "UTF-8"); System.out.println("识别获取结果请求响应:" + StrResponseBody); JSONObject json = JSONObject.parseObject(StrResponseBody); if (json.getJSONObject("result").getInteger("ret") != 0) { System.out.println("识别获取结果报错:" + StrResponseBody); break; } String cur_result = json.getJSONObject("result").getString("result"); if (cur_result != null && cur_result.length() != 0) { allResult.append(parseResult(cur_result)); } ; if (5 == json.getJSONObject("result").getInteger("recStatus")) { break; } } } catch (Exception e) { System.out.println("语音识别获取结果报错:{}" + e); } audioInfo.setSyncid(syncid); audioInfo.setResultGetResult(allResult); return audioInfo; } /** * SessionEnd */ public static void SessionEnd(IatInfo audioInfo, String url, String extendParams) { try { int syncid = audioInfo.getSyncid(); final Base64.Decoder decoder = Base64.getDecoder(); final Base64.Encoder encoder = Base64.getEncoder(); JSONObject json_params = new JSONObject(); json_params.put("appid", appid); json_params.put("cmd", "sse"); json_params.put("extend_params", extendParams); json_params.put("sid", audioInfo.getSid()); json_params.put("svc", svc); json_params.put("auth_id", audioInfo.getAuthId()); json_params.put("syncid", String.valueOf(syncid)); syncid = syncid + 1; JSONObject json_body = new JSONObject(); json_body.put("jsonrpc", "2.0"); json_body.put("method", "deal_request"); json_body.put("params", json_params); json_body.put("id", 4); System.out.println("识别结束会话请求报文:" + json_body.toJSONString()); String responseBody = sendJsonHttpPost(url, json_body.toJSONString()); String StrResponseBody = new String(decoder.decode(responseBody), "UTF-8"); System.out.println("识别结束会话请求响应:" + StrResponseBody); JSONObject json = JSONObject.parseObject(StrResponseBody); if (json.getJSONObject("result").getInteger("ret") != 0) { System.out.println("识别报错:" + StrResponseBody); } } catch (Exception e) { System.out.println("识别结束会话报错:{}" + e); } } public static String sendJsonHttpPost(String url, String json) { CloseableHttpClient httpclient = HttpClients.createDefault(); String responseInfo = null; try { HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-type", "application/json-rpc; charset=utf-8"); httpPost.setHeader("Accept", "application/json-rpc"); if (!scookie.isEmpty()) { httpPost.setHeader("Cookie", scookie); } httpPost.setEntity(new StringEntity(json, Charset.forName("UTF-8"))); CloseableHttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { if (null != entity) { responseInfo = EntityUtils.toString(entity); } } try { if (scookie.isEmpty()) { Header[] headers = response.getHeaders("Set-Cookie"); if ((null != headers) && (headers.length == 1)) { scookie = headers[0].getValue().split(";")[0]; } else { scookie = ""; } } } finally { response.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return responseInfo; } private static ArrayList<String> readFileOnLine(String filePath) {// 输入文件路径 File file = new File(filePath); ArrayList<String> list = new ArrayList<String>(); if (!file.exists()) { System.out.println("file open failed"); return list; } if (file.isDirectory()) { // 获取路径下的所有文件 File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { list.add(files[i].getPath()); } } else { try { FileInputStream fis = new FileInputStream(file); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));// 读取文件数据 String strLine = null; while ((strLine = bufferedReader.readLine()) != null) {// 通过readline按行读取 list.add(strLine); } bufferedReader.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } } return list; } public static void readFile(String path) { if (audio_map.get(path) != null) { return; } File file = new File(path); ArrayList<byte[]> buffers = new ArrayList<byte[]>(); buffers.clear(); int length = 0; try { InputStream stream = new FileInputStream(file); for (; ; ) { byte[] bts = null; bts = new byte[64000];//16k16bit的音频,需要sleep 80ms length = stream.read(bts); if (length == -1) { break; } if (length != bts.length) { //最后一段的length < bts.length byte[] tmp = new byte[length]; System.arraycopy(bts, 0, tmp, 0, length); buffers.add(tmp); } else { buffers.add(bts); } } if (buffers.size() == 1) { byte[] bts = new byte[1]; buffers.add(bts); } stream.close(); audio_map.put(path, buffers); } catch (Exception e) { e.printStackTrace(); } } public static String getUUID() { return UUID.randomUUID().toString().replace("-", ""); } private static synchronized int getnum() { int n = (num % filesize); ++num; return n; } private static String parseResult(String cur_result) { String txt_result = ""; if (!"".equals(cur_result)) { JSONObject jsonObject = JSON.parseObject(cur_result); String ws = jsonObject.getString("ws"); if (ws != null && !"".equals(ws)) { JSONArray jsonArray = JSONObject.parseArray(ws); for (Object object : jsonArray) { JSONObject temp = (JSONObject) object; String cw = temp.getString("cw"); JSONArray jsonArrayCW = JSONObject.parseArray(cw); for (Object objectCW : jsonArrayCW) { JSONObject tempCW = (JSONObject) objectCW; String w = tempCW.getString("w"); txt_result = txt_result + w; } } } } return txt_result; } } 新增一个类,通过新增的类 来调用这个类的main方法
最新发布
10-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值