sourcecode

JSON 문자열을 HashMap으로 변환

copyscript 2022. 7. 27. 23:52
반응형

JSON 문자열을 HashMap으로 변환

Java를 사용하고 있으며 JSON이라는 문자열이 있습니다.

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

그러면 자바 맵:

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

JSONObject의 모든 데이터를 HashMap에 저장하고 싶습니다.

이거에 대한 코드를 제공할 수 있는 사람?사용하고 싶다org.json도서관.

재귀적 방법:

public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
    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.keys();
    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) throws JSONException {
    List<Object> list = new ArrayList<Object>();
    for(int i = 0; i < array.length(); 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;
}

잭슨 라이브러리 사용:

import com.fasterxml.jackson.databind.ObjectMapper;

Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, HashMap.class);

Gson을 사용하여 다음 작업을 수행할 수 있습니다.

Map<String, Object> retMap = new Gson().fromJson(
    jsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);

이것이 효과가 있기를 바랍니다.이것을 사용해 보세요.

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

str, JSON 문자열

이렇게 간단하게 이메일 ID를 원하시면

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

그냥 Gson 사용했어.

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

다음은 Vikas의 코드를 JSR 353으로 포팅한 것입니다.

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;
    }
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;


public class JsonUtils {

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

        if(json != null) {
            retMap = toMap(json);
        }
        return retMap;
    }

    public static Map<String, Object> toMap(JSONObject object) {
        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;
    }
}

다음 코드를 사용해 보십시오.

 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();
                }

잭슨을 사용하여 변환:

JSONObject obj = new JSONObject().put("abc", "pqr").put("xyz", 5);

Map<String, Object> map = new ObjectMapper().readValue(obj.toString(), new TypeReference<Map<String, Object>>() {});

최신 정보:사용한 적이 있다FasterXML Jackson Databind2.12.3 JSON 문자열을 Map으로 변환하고 Map을 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 문자열을 맵으로 변환

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);
            }
        }
    }    
    
}

Google.gson에서 HashMap으로.

임의의 변환이 가능합니다.JSON로.mapJackson 라이브러리를 다음과 같이 사용합니다.

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 의존관계:

<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>

이게 도움이 되길 바라.해피 코딩 :)

Jackson API는 다음과 같은 용도로도 사용할 수 있습니다.

    final String json = "....your json...";
    final ObjectMapper mapper = new ObjectMapper();
    final MapType type = mapper.getTypeFactory().constructMapType(
        Map.class, String.class, Object.class);
    final Map<String, Object> data = mapper.readValue(json, type);

재귀가 싫은 경우 Stack 및 javax.json을 사용하여 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);
    }
}

오래된 답변이 있습니다.javax.json여기에 게시되지만 변환만 됩니다.JsonArray그리고.JsonObject, 그러나 아직 있습니다.JsonString,JsonNumber,그리고.JsonValuewrapper 클래스가 출력에 표시됩니다.만약 이것들을 제거하고 싶다면, 여기 모든 것을 풀 수 있는 해결책이 있습니다.

그 외에도 Java 8 스트림을 사용하며 단일 방식으로 포함되어 있습니다.

/**
 * Convert a JsonValue into a “plain” Java structure (using Map and List).
 * 
 * @param value The JsonValue, not <code>null</code>.
 * @return Map, List, String, Number, Boolean, or <code>null</code>.
 */
public static Object toObject(JsonValue value) {
    Objects.requireNonNull(value, "value was null");
    switch (value.getValueType()) {
    case ARRAY:
        return ((JsonArray) value)
                .stream()
                .map(JsonUtils::toObject)
                .collect(Collectors.toList());
    case OBJECT:
        return ((JsonObject) value)
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Entry::getKey,
                        e -> toObject(e.getValue())));
    case STRING:
        return ((JsonString) value).getString();
    case NUMBER:
        return ((JsonNumber) value).numberValue();
    case TRUE:
        return Boolean.TRUE;
    case FALSE:
        return Boolean.FALSE;
    case NULL:
        return null;
    default:
        throw new IllegalArgumentException("Unexpected type: " + value.getValueType());
    }
}

Google gson 라이브러리를 사용하여 json 개체를 변환할 수 있습니다.

https://code.google.com/p/google-gson/

잭슨과 같은 다른 도서관들도 이용할 수 있다.

이렇게 해도 지도로는 변환되지 않습니다.하지만 당신은 당신이 원하는 모든 것을 할 수 있습니다.

간결하고 편리한 기능:

/**
 * @param jsonThing can be a <code>JsonObject</code>, a <code>JsonArray</code>,
 *                     a <code>Boolean</code>, a <code>Number</code>,
 *                     a <code>null</code> or a <code>JSONObject.NULL</code>.
 * @return <i>Appropriate Java Object</i>, that may be a <code>Map</code>, a <code>List</code>,
 * a <code>Boolean</code>, a <code>Number</code> or a <code>null</code>.
 */
public static Object jsonThingToAppropriateJavaObject(Object jsonThing) throws JSONException {
    if (jsonThing instanceof JSONArray) {
        final ArrayList<Object> list = new ArrayList<>();

        final JSONArray jsonArray = (JSONArray) jsonThing;
        final int l = jsonArray.length();
        for (int i = 0; i < l; ++i) list.add(jsonThingToAppropriateJavaObject(jsonArray.get(i)));
        return list;
    }

    if (jsonThing instanceof JSONObject) {
        final HashMap<String, Object> map = new HashMap<>();

        final Iterator<String> keysItr = ((JSONObject) jsonThing).keys();
        while (keysItr.hasNext()) {
            final String key = keysItr.next();
            map.put(key, jsonThingToAppropriateJavaObject(((JSONObject) jsonThing).get(key)));
        }
        return map;
    }

    if (JSONObject.NULL.equals(jsonThing)) return null;

    return jsonThing;
}

@Vikas Gupta님 감사합니다.

다음 파서는 파일을 읽고 일반 파서로 해석합니다.JsonElement, 구글의JsonParser.parse생성된 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);
    }
}

이것은 오래된 질문이고 아마도 누군가와 관련이 있을 것이다.
HashMap 문자열이 있다고 가정합니다.hash및 Json ObjectjsonObject.

1) 키 리스트를 정의합니다.
예:

ArrayList<String> keyArrayList = new ArrayList<>();  
keyArrayList.add("key0");   
keyArrayList.add("key1");  

2) Foreach 루프 생성, 추가hash부터jsonObject포함:

for(String key : keyArrayList){  
    hash.put(key, jsonObject.getString(key));
}

그게 내 접근법이야. 그게 질문에 답하길 바라.

다음과 같은 이메일 목록을 가지고 있다고 상상해 보세요.프로그래밍 언어에 얽매이지 않고

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

다음은 JAVA 코드입니다.json을 맵으로 변환하기 위한 코드입니다.

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

json-simple을 사용하여 데이터를 Map으로 변환하고 Map을 JSON으로 변환할 수 있습니다.

try
{
    JSONObject obj11 = new JSONObject();
    obj11.put(1, "Kishan");
    obj11.put(2, "Radhesh");
    obj11.put(3, "Sonal");
    obj11.put(4, "Madhu");

    Map map = new  HashMap();

    obj11.toJSONString();

    map = obj11;

    System.out.println(map.get(1));


    JSONObject obj12 = new JSONObject();

    obj12 = (JSONObject) map;

    System.out.println(obj12.get(1));
}
catch(Exception e)
{
    System.err.println("EROR : 01 :"+e);
}

언급URL : https://stackoverflow.com/questions/21720759/convert-a-json-string-to-a-hashmap

반응형