如何在android中将HashMap转换为json数组?

San*_*eep 18 java arrays android json

我想HashMap转换为json数组,我的代码如下:

Map<String, String> map = new HashMap<String, String>();

map.put("first", "First Value");

map.put("second", "Second Value");
Run Code Online (Sandbox Code Playgroud)

我试过这个但是没用.有解决方案吗

JSONArray mJSONArray = new JSONArray(Arrays.asList(map));
Run Code Online (Sandbox Code Playgroud)

Pra*_*ani 44

试试这个,

public JSONObject (Map copyFrom) 
Run Code Online (Sandbox Code Playgroud)

通过复制给定映射中的所有名称/值映射来创建新的JSONObject.

参数copyFrom一个映射,其键的类型为String,其值为支持的类型.

如果任何地图的键为空,则抛出NullPointerException.

基本用法:

JSONObject obj=new JSONObject(yourmap);
Run Code Online (Sandbox Code Playgroud)

从JSONObject获取json数组

编辑:

JSONArray array=new JSONArray(obj.toString());
Run Code Online (Sandbox Code Playgroud)

编辑:(如果发现异常,那么您可以通过@ krb686在评论中更改)

JSONArray array=new JSONArray("["+obj.toString()+"]");
Run Code Online (Sandbox Code Playgroud)


sen*_*eco 14

自从androiad API Lvl 19以来,你可以简单地做到new JSONObject(new HashMap()).但是对于较旧的API lvls,你得到了丑陋的结果(简单地将toString应用于每个非原始值).

我从JSONObject和JSONArray收集了方法,以简化和精美的结果.您可以使用我的解决方案类:

package you.package.name;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;

public class JsonUtils
{
    public static JSONObject mapToJson(Map<?, ?> data)
    {
        JSONObject object = new JSONObject();

        for (Map.Entry<?, ?> entry : data.entrySet())
        {
            /*
             * Deviate from the original by checking that keys are non-null and
             * of the proper type. (We still defer validating the values).
             */
            String key = (String) entry.getKey();
            if (key == null)
            {
                throw new NullPointerException("key == null");
            }
            try
            {
                object.put(key, wrap(entry.getValue()));
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }

        return object;
    }

    public static JSONArray collectionToJson(Collection data)
    {
        JSONArray jsonArray = new JSONArray();
        if (data != null)
        {
            for (Object aData : data)
            {
                jsonArray.put(wrap(aData));
            }
        }
        return jsonArray;
    }

    public static JSONArray arrayToJson(Object data) throws JSONException
    {
        if (!data.getClass().isArray())
        {
            throw new JSONException("Not a primitive data: " + data.getClass());
        }
        final int length = Array.getLength(data);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < length; ++i)
        {
            jsonArray.put(wrap(Array.get(data, i)));
        }

        return jsonArray;
    }

    private static Object wrap(Object o)
    {
        if (o == null)
        {
            return null;
        }
        if (o instanceof JSONArray || o instanceof JSONObject)
        {
            return o;
        }
        try
        {
            if (o instanceof Collection)
            {
                return collectionToJson((Collection) o);
            }
            else if (o.getClass().isArray())
            {
                return arrayToJson(o);
            }
            if (o instanceof Map)
            {
                return mapToJson((Map) o);
            }
            if (o instanceof Boolean ||
                    o instanceof Byte ||
                    o instanceof Character ||
                    o instanceof Double ||
                    o instanceof Float ||
                    o instanceof Integer ||
                    o instanceof Long ||
                    o instanceof Short ||
                    o instanceof String)
            {
                return o;
            }
            if (o.getClass().getPackage().getName().startsWith("java."))
            {
                return o.toString();
            }
        }
        catch (Exception ignored)
        {
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,如果将mapToJson()方法应用于Map,则可以得到如下结果:

{
  "int": 1,
  "Integer": 2,
  "String": "a",
  "int[]": [1,2,3],
  "Integer[]": [4, 5, 6],
  "String[]": ["a","b","c"],
  "Collection": [1,2,"a"],
  "Map": {
    "b": "B",
    "c": "C",
    "a": "A"
  }
}
Run Code Online (Sandbox Code Playgroud)