我使用Java,我有一个JSON字符串:

{
"name" : "abc" ,
"email id " : ["abc@gmail.com","def@gmail.com","ghi@gmail.com"]
}

然后是我的Java地图:

Map<String, Object> retMap = new HashMap<String, Object>();

我想把所有来自JSONObject的数据存储在那个HashMap中。

有人能为此提供代码吗?我想用org。json库。


当前回答

如果你讨厌递归-使用Stack和javax。将一个json字符串转换成一个地图列表:

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import javax.json.Json;
import javax.json.stream.JsonParser;

public class TestCreateObjFromJson {
    public static List<Map<String,Object>> extract(InputStream is) {
        List extracted = new ArrayList<>();
        JsonParser parser = Json.createParser(is);

        String nextKey = "";
        Object nextval = "";
        Stack s = new Stack<>();
        while(parser.hasNext()) {
            JsonParser.Event event = parser.next();
            switch(event) {
                case START_ARRAY :  List nextList = new ArrayList<>();
                                    if(!s.empty()) {
                                        // If this is not the root object, add it to tbe parent object
                                        setValue(s,nextKey,nextList);
                                    }
                                    s.push(nextList);
                                    break;
                case START_OBJECT : Map<String,Object> nextMap = new HashMap<>();
                                    if(!s.empty()) {
                                        // If this is not the root object, add it to tbe parent object
                                        setValue(s,nextKey,nextMap);
                                    }
                                    s.push(nextMap);
                                    break;
                case KEY_NAME : nextKey = parser.getString();
                                break;
                case VALUE_STRING : setValue(s,nextKey,parser.getString());
                                    break;
                case VALUE_NUMBER : setValue(s,nextKey,parser.getLong());
                                    break;
                case VALUE_TRUE :   setValue(s,nextKey,true);
                                    break;
                case VALUE_FALSE :  setValue(s,nextKey,false);
                                    break;
                case VALUE_NULL :   setValue(s,nextKey,"");
                                    break;
                case END_OBJECT :   
                case END_ARRAY  :   if(s.size() > 1) {
                                        // If this is not a root object, move up
                                        s.pop(); 
                                    } else {
                                        // If this is a root object, add ir ro rhw final 
                                        extracted.add(s.pop()); 
                                    }
                default         :   break;
            }
        }

        return extracted;
    }

    private static void setValue(Stack s, String nextKey, Object v) {
        if(Map.class.isAssignableFrom(s.peek().getClass()) ) ((Map)s.peek()).put(nextKey, v);
        else ((List)s.peek()).add(v);
    }
}

其他回答

如果你想要无库版本,这里是与regex的解决方案:

public static HashMap<String, String> jsonStringToMap(String inputJsonString) {
    final String regex = "(?:\\\"|\\')(?<key>[\\w\\d]+)(?:\\\"|\\')(?:\\:\\s*)(?:\\\"|\\')?(?<value>[\\w\\s-]*)(?:\\\"|\\')?";
    HashMap<String, String> map = new HashMap<>();
    final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
    final Matcher matcher = pattern.matcher(inputJsonString);

    while (matcher.find()) {
        for (int i = 1; i <= matcher.groupCount(); i++) {
            map.put(matcher.group("key"), matcher.group("value"));
        }
    }
    return map;
}

试试下面的代码:

 Map<String, String> params = new HashMap<String, String>();
                try
                {

                   Iterator<?> keys = jsonObject.keys();

                    while (keys.hasNext())
                    {
                        String key = (String) keys.next();
                        String value = jsonObject.getString(key);
                        params.put(key, value);

                    }


                }
                catch (Exception xx)
                {
                    xx.toString();
                }

下面的解析器读取一个文件,使用谷歌的JsonParser将其解析为通用的JsonElement。解析方法,然后将生成JSON中的所有项转换为原生Java List<object>或Map<String, object>。

注意:下面的代码是基于Vikas Gupta的回答。

GsonParser.java

import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;

public class GsonParser {
    public static void main(String[] args) {
        try {
            print(loadJsonArray("data_array.json", true));
            print(loadJsonObject("data_object.json", true));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void print(Object object) {
        System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(object).toString());
    }

    public static Map<String, Object> loadJsonObject(String filename, boolean isResource)
            throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
        return jsonToMap(loadJson(filename, isResource).getAsJsonObject());
    }

    public static List<Object> loadJsonArray(String filename, boolean isResource)
            throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
        return jsonToList(loadJson(filename, isResource).getAsJsonArray());
    }

    private static JsonElement loadJson(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
        return new JsonParser().parse(new InputStreamReader(FileLoader.openInputStream(filename, isResource), "UTF-8"));
    }

    public static Object parse(JsonElement json) {
        if (json.isJsonObject()) {
            return jsonToMap((JsonObject) json);
        } else if (json.isJsonArray()) {
            return jsonToList((JsonArray) json);
        }

        return null;
    }

    public static Map<String, Object> jsonToMap(JsonObject jsonObject) {
        if (jsonObject.isJsonNull()) {
            return new HashMap<String, Object>();
        }

        return toMap(jsonObject);
    }

    public static List<Object> jsonToList(JsonArray jsonArray) {
        if (jsonArray.isJsonNull()) {
            return new ArrayList<Object>();
        }

        return toList(jsonArray);
    }

    private static final Map<String, Object> toMap(JsonObject object) {
        Map<String, Object> map = new HashMap<String, Object>();

        for (Entry<String, JsonElement> pair : object.entrySet()) {
            map.put(pair.getKey(), toValue(pair.getValue()));
        }

        return map;
    }

    private static final List<Object> toList(JsonArray array) {
        List<Object> list = new ArrayList<Object>();

        for (JsonElement element : array) {
            list.add(toValue(element));
        }

        return list;
    }

    private static final Object toPrimitive(JsonPrimitive value) {
        if (value.isBoolean()) {
            return value.getAsBoolean();
        } else if (value.isString()) {
            return value.getAsString();
        } else if (value.isNumber()){
            return value.getAsNumber();
        }

        return null;
    }

    private static final Object toValue(JsonElement value) {
        if (value.isJsonNull()) {
            return null;
        } else if (value.isJsonArray()) {
            return toList((JsonArray) value);
        } else if (value.isJsonObject()) {
            return toMap((JsonObject) value);
        } else if (value.isJsonPrimitive()) {
            return toPrimitive((JsonPrimitive) value);
        }

        return null;
    }
}

FileLoader.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;

public class FileLoader {
    public static Reader openReader(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException {
        return openReader(filename, isResource, "UTF-8");
    }

    public static Reader openReader(String filename, boolean isResource, String charset) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException {
        return new InputStreamReader(openInputStream(filename, isResource), charset);
    }

    public static InputStream openInputStream(String filename, boolean isResource) throws FileNotFoundException, MalformedURLException {
        if (isResource) {
            return FileLoader.class.getClassLoader().getResourceAsStream(filename);
        }

        return new FileInputStream(load(filename, isResource));
    }

    public static String read(String path, boolean isResource) throws IOException {
        return read(path, isResource, "UTF-8");
    }

    public static String read(String path, boolean isResource, String charset) throws IOException {
        return read(pathToUrl(path, isResource), charset);
    }

    @SuppressWarnings("resource")
    protected static String read(URL url, String charset) throws IOException {
        return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
    }

    protected static File load(String path, boolean isResource) throws MalformedURLException {
        return load(pathToUrl(path, isResource));
    }

    protected static File load(URL url) {
        try {
            return new File(url.toURI());
        } catch (URISyntaxException e) {
            return new File(url.getPath());
        }
    }

    private static final URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
        if (isResource) {
            return FileLoader.class.getClassLoader().getResource(path);
        }

        return new URL("file:/" + path);
    }
}

最新更新:我已经使用fastxmljackson Databind2.12.3转换JSON字符串到映射,映射到JSON字符串。

// javax.ws.rs.core.Response clientresponse = null; // Read JSON with Jersey 2.0 (JAX-RS 2.0)
// String json_string = clientresponse.readEntity(String.class);
String json_string = "[\r\n"
        + "{\"domain\":\"stackoverflow.com\", \"userId\":5081877, \"userName\":\"Yash\"},\r\n"
        + "{\"domain\":\"stackoverflow.com\", \"userId\":6575754, \"userName\":\"Yash\"}\r\n"
        + "]";
System.out.println("Input/Response JSON string:"+json_string);
ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
//java.util.Map<String, String> map = mapper.readValue(json_string, java.util.Map.class);
List<Map<String, Object>> listOfMaps = mapper.readValue(json_string, new com.fasterxml.jackson.core.type.TypeReference< List<Map<String, Object>>>() {});

System.out.println("fasterxml JSON string to List of Map:"+listOfMaps);

String json = mapper.writeValueAsString(listOfMaps);
System.out.println("fasterxml List of Map to JSON string:[compact-print]"+json);

json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(listOfMaps);
System.out.println("fasterxml List of Map to JSON string:[pretty-print]"+json);

输出:

Input/Response JSON string:[
{"domain":"stackoverflow.com", "userId":5081877, "userName":"Yash"},
{"domain":"stackoverflow.com", "userId":6575754, "userName":"Yash"}
]
fasterxml JSON string to List of Map:[{domain=stackoverflow.com, userId=5081877, userName=Yash}, {domain=stackoverflow.com, userId=6575754, userName=Yash}]
fasterxml List of Map to JSON string:[compact-print][{"domain":"stackoverflow.com","userId":5081877,"userName":"Yash"},{"domain":"stackoverflow.com","userId":6575754,"userName":"Yash"}]
fasterxml List of Map to JSON string:[pretty-print][ {
  "domain" : "stackoverflow.com",
  "userId" : 5081877,
  "userName" : "Yash"
}, {
  "domain" : "stackoverflow.com",
  "userId" : 6575754,
  "userName" : "Yash"
} ]

将JSON字符串转换为Map

public static java.util.Map<String, Object> jsonString2Map( String jsonString ) throws org.json.JSONException {
    Map<String, Object> keys = new HashMap<String, Object>(); 
    
    org.json.JSONObject jsonObject = new org.json.JSONObject( jsonString ); // HashMap
    java.util.Iterator<?> keyset = jsonObject.keys(); // HM
    
    while (keyset.hasNext()) {
        String key =  (String) keyset.next();
        Object value = jsonObject.get(key);
        System.out.print("\n Key : "+key);
        if ( value instanceof org.json.JSONObject ) {
            System.out.println("Incomin value is of JSONObject : ");
            keys.put( key, jsonString2Map( value.toString() ));
        } else if ( value instanceof org.json.JSONArray) {
            org.json.JSONArray jsonArray = jsonObject.getJSONArray(key);
            //JSONArray jsonArray = new JSONArray(value.toString());
            keys.put( key, jsonArray2List( jsonArray ));
        } else {
            keyNode( value);
            keys.put( key, value );
        }
    }
    return keys;
}

将JSON数组转换为列表

public static java.util.List<Object> jsonArray2List( org.json.JSONArray arrayOFKeys ) throws org.json.JSONException {
    System.out.println("Incoming value is of JSONArray : =========");
    java.util.List<Object> array2List = new java.util.ArrayList<Object>();
    for ( int i = 0; i < arrayOFKeys.length(); i++ )  {
        if ( arrayOFKeys.opt(i) instanceof org.json.JSONObject ) {
            Map<String, Object> subObj2Map = jsonString2Map(arrayOFKeys.opt(i).toString());
            array2List.add(subObj2Map);
        } else if ( arrayOFKeys.opt(i) instanceof org.json.JSONArray ) {
            java.util.List<Object> subarray2List = jsonArray2List((org.json.JSONArray) arrayOFKeys.opt(i));
            array2List.add(subarray2List);
        } else {
            keyNode( arrayOFKeys.opt(i) );
            array2List.add( arrayOFKeys.opt(i) );
        }
    }
    return array2List;
}
public static Object keyNode(Object o) {
    if (o instanceof String || o instanceof Character) return (String) o;
    else if (o instanceof Number) return (Number) o;
    else return o;
}

显示任意格式的JSON

public static void displayJSONMAP( Map<String, Object> allKeys ) throws Exception{
    Set<String> keyset = allKeys.keySet(); // HM$keyset
    if (! keyset.isEmpty()) {
        Iterator<String> keys = keyset.iterator(); // HM$keysIterator
        while (keys.hasNext()) {
            String key = keys.next();
            Object value = allKeys.get( key );
            if ( value instanceof Map ) {
                System.out.println("\n Object Key : "+key);
                    displayJSONMAP(jsonString2Map(value.toString()));
            }else if ( value instanceof List ) {
                System.out.println("\n Array Key : "+key);
                JSONArray jsonArray = new JSONArray(value.toString());
                jsonArray2List(jsonArray);
            }else {
                System.out.println("key : "+key+" value : "+value);
            }
        }
    }    
    
}

谷歌。gson到HashMap。

以下是移植到JSR 353的Vikas代码:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.json.JsonArray;
import javax.json.JsonException;
import javax.json.JsonObject;

public class JsonUtils {
    public static Map<String, Object> jsonToMap(JsonObject json) {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JsonObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }

    public static Map<String, Object> toMap(JsonObject object) throws JsonException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keySet().iterator();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JsonArray) {
                value = toList((JsonArray) value);
            }

            else if(value instanceof JsonObject) {
                value = toMap((JsonObject) value);
            }
            map.put(key, value);
        }
        return map;
    }

    public static List<Object> toList(JsonArray array) {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.size(); i++) {
            Object value = array.get(i);
            if(value instanceof JsonArray) {
                value = toList((JsonArray) value);
            }

            else if(value instanceof JsonObject) {
                value = toMap((JsonObject) value);
            }
            list.add(value);
        }
        return list;
    }
}