如何在android中将HashMap转换为json数组? [英] How to convert HashMap to json Array in android?
本文介绍了如何在android中将HashMap转换为json数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I want to convert HashMap to json array my code is as follow:
Map<String, String> map = new HashMap<String, String>();
map.put("first", "First Value");
map.put("second", "Second Value");
我已经试过了,但是没有用.有什么解决办法吗?
JSONArray mJSONArray = new JSONArray(Arrays.asList(map));
推荐答案
试试这个,
public JSONObject (Map copyFrom)
通过复制给定映射中的所有名称/值映射来创建一个新的 JSONObject.
Creates a new JSONObject by copying all name/value mappings from the given map.
参数copyFrom 一个映射,其键是 String 类型,其值是受支持的类型.
Parameters copyFrom a map whose keys are of type String and whose values are of supported types.
投掷如果地图的任何键为空,则为 NullPointerException.
Throws NullPointerException if any of the map's keys are null.
基本用法:
JSONObject obj=new JSONObject(yourmap);
从 JSONObject 中获取 json 数组
JSONArray array=new JSONArray(obj.toString());
(如果发现异常,则您可以更改为@krb686 在评论中提及的内容)
(If found Exception then You can change as mention in comment by @krb686)
JSONArray array=new JSONArray("["+obj.toString()+"]");
这篇关于如何在android中将HashMap转换为json数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文