- 这是很常用的一个功能,我使用的是Gson来实现
- 首先是jar包,可以通过maven来获得
- java map对象语json互相转换关键代码如下
BufferedReader streamReader = new BufferedReader(new InputStreamReader(input_stream,"UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); // mapObj = JSONObject.parseObject(responseStrBuilder.toString(),Map.class); mapObj = gson.fromJson(responseStrBuilder.toString(), HashMap.class);
json_string = gson.toJson(mapObj);
-
工具类
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class ConvertUtils { private static Gson gson = new Gson(); public static HashMap get_request_json_object(InputStream input_stream){ HashMap mapObj=null; try { BufferedReader streamReader = new BufferedReader(new InputStreamReader(input_stream,"UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); // mapObj = JSONObject.parseObject(responseStrBuilder.toString(),Map.class); mapObj = gson.fromJson(responseStrBuilder.toString(), HashMap.class); } catch (Exception e) { e.printStackTrace(); } return mapObj; } public static String build_request_json_object(Map mapObj) { String json_string = null; try { json_string = gson.toJson(mapObj); } catch (Exception e) { e.printStackTrace(); } return json_string; } }
-
js map 对象 和json 的互相转换也简单
两者互转(字符串与对象的互转): var json2map=JSON.parse(json); var map2json=JSON.stringify(map);
ssm 开发经验 java,js中 map 对象转换成和json字符串的互相转换
最新推荐文章于 2024-06-25 00:00:00 发布