作者:东张西望 | 来源:互联网 | 2024-12-02 20:20
今天,同事问我json的问题。遍历json数组,解决完以后。我想到了 json转Map这个问题。写一下,发现效果还行 那个发上来看看吧。如果想省事的话,用阿里的FastJson 我感觉也是不错的 ,网上教程很多,我就不多说了。
注意这是Android自带的json包
import org. json. JSONArray; import org. json. JSONException; import org. json. JSONObject;
在这里说一下,JSONObject是键值对应的,符合map键值对应, JSONArray 是没有key的。这里,要转成map的话,我是按照JSONArray里面的元素顺序,给他们key,key就是他们的位置
看代码:
Map< String, Object> jsonToMap ( String content) { content = content. trim ( ) ; Map< String, Object> result = new HashMap < > ( ) ; try { if ( content. charAt ( 0 ) == '[' ) { JSONArray jsonArray = new JSONArray ( content) ; for ( int i = 0 ; i < jsonArray. length ( ) ; i++ ) { Object value = jsonArray. get ( i) ; if ( value instanceof JSONArray || value instanceof JSONObject ) { result. put ( i + "" , jsonToMap ( value. toString ( ) . trim ( ) ) ) ; } else { result. put ( i + "" , jsonArray. getString ( i) ) ; } } } else if ( content. charAt ( 0 ) == '{' ) { JSONObject jsonObject = new JSONObject ( content) ; Iterator< String> iterator = jsonObject. keys ( ) ; while ( iterator. hasNext ( ) ) { String key = iterator. next ( ) ; Object value = jsonObject. get ( key) ; if ( value instanceof JSONArray || value instanceof JSONObject ) { result. put ( key, jsonToMap ( value. toString ( ) . trim ( ) ) ) ; } else { result. put ( key, value. toString ( ) . trim ( ) ) ; } } } else { Log. e ( "异常" , "json2Map: 字符串格式错误" ) ; } } catch ( JSONException e) { Log. e ( "异常" , "json2Map: " , e) ; result = null; } return result; }
使用 JSONObject jsonObject = new JSONObject ( ) ; jsonObject. put ( "one" , "哈哈哈" ) ; jsonObject. put ( "two" , "yyy" ) ; JSONArray jsonArray = new JSONArray ( ) ; jsonArray. put ( "数组内容1" ) ; jsonArray. put ( "数组内容2" ) ; jsonArray. put ( "数组内容3" ) ; JSONObject inner = new JSONObject ( ) ; inner. put ( "内置" , "我是内置的" ) ; inner. put ( "内置数组" , new JSONArray ( ) . put ( 1 ) ) ; jsonArray. put ( inner) ; jsonObject. put ( "three" , jsonArray) ; Map< String, Object> map = jsonToMap ( jsonObject. toString ( ) ) ; map. forEach ( ( s, o) - > { Zprint. log ( this . getClass ( ) , s, o) ; } ) ;
输出结果
完全符合要求。
是不是很好奇 我的控制台怎么是这种格式的,这是我自定义的log输出工具,可以看我以前的博客。 Android 输出日志 带类名 方法名 参数 行号,点击直接到代码行
如果有不懂的,可以关注我的公众号 “知我饭否” 向我留言。我会每天更新一些文章,有兴趣的可以 微信 搜索"知我饭否" or 扫描我的 博客头像 。