From 33a2d166c75a78b5acaf8964de04ace82463180c Mon Sep 17 00:00:00 2001 From: ggb <854357635@qq.com> Date: Thu, 18 Jul 2019 19:17:04 +0800 Subject: [PATCH] finishencode --- .../linwancunyi/util/JsonTransformation.java | 44 ++++++++++++++++--- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/linwankaifa/linwancunyi/util/JsonTransformation.java b/app/src/main/java/com/linwankaifa/linwancunyi/util/JsonTransformation.java index 0b07c11..9265b5c 100644 --- a/app/src/main/java/com/linwankaifa/linwancunyi/util/JsonTransformation.java +++ b/app/src/main/java/com/linwankaifa/linwancunyi/util/JsonTransformation.java @@ -1,41 +1,75 @@ package com.linwankaifa.linwancunyi.util; +import android.util.Base64; + import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; +import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class JsonTransformation {//json转换,以实体Manager为例 + static byte[] textByte = new byte[0]; + static String endodeStr; + static String decodeStr; public static String objectToJson(T clazz)//object to json { Gson gson = new Gson(); - String gsonStr = gson.toJson(clazz); - return gsonStr; + endodeStr = gson.toJson(clazz); + try { + textByte = endodeStr.getBytes("UTF-8"); + } catch ( + UnsupportedEncodingException e) { + e.printStackTrace(); + return ""; + } + return Base64.encodeToString(textByte, Base64.NO_WRAP); } public static T jsonToObject(String gsonStr, Class clazz)//json to object { Gson gson = new Gson(); - return gson.fromJson(gsonStr, clazz); + try { + decodeStr = new String(Base64.decode(gsonStr.toString().replace("\r\n", ""), Base64.DEFAULT), "utf-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + return null; + } + return gson.fromJson(decodeStr, clazz); } public static String listToJson(List list)//list to json { + Gson gson = new Gson(); - return gson.toJson(list); + endodeStr = gson.toJson(list); + try { + textByte = endodeStr.getBytes("UTF-8"); + } catch ( + UnsupportedEncodingException e) { + e.printStackTrace(); + return ""; + } + return Base64.encodeToString(textByte, Base64.NO_WRAP); } public static List jsonToList(String gsonStr, Class clazz)//json to list { + try { + decodeStr = new String(Base64.decode(gsonStr.toString().replace("\r\n", ""), Base64.DEFAULT), "utf-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + return null; + } List list = new ArrayList(); try { Gson gson = new Gson(); - JsonArray arry = new JsonParser().parse(gsonStr).getAsJsonArray(); + JsonArray arry = new JsonParser().parse(decodeStr).getAsJsonArray(); for (JsonElement jsonElement : arry) { list.add(gson.fromJson(jsonElement, clazz)); } -- Gitee