0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java HashMap 转 js json格式

Last updated at Posted at 2018-01-09

##背景
我在安卓的开发中有个需求,安卓本地端的数据需要和WebView的javascript的api进行交互。而javascript的交互数据通常是以jason格式进行的,所以需要把java中的对象数据转为字符串的jason格式。
目前的问题是,javascript的写法比较灵活,直接写一段字符串然后定义自己想写的key,针对每一个key,你都可以写自己想写的数据格式,比如字符串,数组,object,数组等。但是对于以严谨为要求的java来说,这似乎变得不是那么理所应当了。

スクリーンショット 2018-01-09 11.57.49.png

目前我所知道的最简单的办法就是HashMap和JSONObject这两个类来实现
简单来说的话就是把想要组成jason的变量放到一个HashMap类型的对象里,然后再用JSONObject对这个对象进行加工,得到js能够处理的json字符串

スクリーンショット 2018-01-09 14.11.50.png

convert.java
        //first you construct the HashMap data
        HashMap<String,Object> hashmap = new HashMap<String,Object>();
        hashmap.put("name","syoui");
        hashmap.put("age",27);
        int[] checkInList = {1,3,5,7,8,10,12};
        hashmap.put("checkInList",checkInList);

        //second you convert the HashMap data into String json data
        JSONObject jsonObject = new JSONObject(hashmap);
        Log.d("the convert result",jsonObject.toString());

日志显示結果 D/the convert result: {"name":"syoui","checkInList":[1,3,5,7,8,10,12],"age":27}

另外HashMap里是支持嵌套HashMap的,这种就是指定一个key下面再次套用HashMap所以说,HashMap的写法会让你有一种回到写js的感觉

convert.java
        HashMap<String,Object> sub_hash_map = new HashMap<String,Object>();
        sub_hash_map.put("name","liaoliao");
        sub_hash_map.put("age",30);
        int[] sub_check_list = {2,4,6,9,11};
        sub_hash_map.put("checkInList",sub_check_list);
        hashmap.put("child",sub_hash_map);

日志显示結果 D/the convert result: {"name":"syoui","ticket":null,"age":27,"child":{"name":"liaoliao","checkInList":[2,4,6,9,11],"age":30},"checkInList":[1,3,5,7,8,10,12]}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?