我使用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库。


当前回答

想象一下你有如下的邮件列表。不受任何编程语言的限制,

emailsList = ["abc@gmail.com","def@gmail.com","ghi@gmail.com"]

下面是JAVA代码-用于将json转换为map

JSONObject jsonObj = new JSONObject().put("name","abc").put("email id",emailsList);
Map<String, Object> s = jsonObj.getMap();

其他回答

我只用了Gson

HashMap<String, Object> map = new Gson().fromJson(json.toString(), HashMap.class);

You can convert any JSON to map by using Jackson library as below: String json = "{\r\n\"name\" : \"abc\" ,\r\n\"email id \" : [\"abc@gmail.com\",\"def@gmail.com\",\"ghi@gmail.com\"]\r\n}"; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = new HashMap<String, Object>(); // convert JSON string to Map map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {}); System.out.println(map); Maven Dependencies for Jackson : <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.5.3</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.3</version> <scope>compile</scope> </dependency> Hope this will help. Happy coding :)

最新更新:我已经使用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。

希望这能起作用,试试这个:

import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);

str,你的JSON字符串

就这么简单,如果你想要电子邮件,

String emailIds = response.get("email id").toString();

以下是移植到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;
    }
}