【问题标题】:Convert a JSON String to a HashMap将 JSON 字符串转换为 HashMap
【发布时间】:2014-03-10 08:31:19
【问题描述】:

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

【问题讨论】:

  • 我不知道为什么 json.org JSONObject 没有私有 map 成员变量的 getter...
  • Kotlin 中的解决方案请检查此 使用 gson stackoverflow.com/a/53763826/8052227
  • 但是,当JSONObject 似乎是完全不需要的多余类型时,为什么还要问这个问题呢?使用任意数量的优秀 Java JSON 库(如 Jackson、GSON、Genson、Moshi)将 JSON 读取为 Map 很简单。那么为什么 OP “想要”使用 org.json?
  • @staxMan,由于组织政策,有时您只能使用内置库。因此,我只能使用 org.json。
  • @VikasGupta 好的,如果在这样的平台上运行(可能是 Android),那是有道理的

标签: java json dictionary


【解决方案1】:

我几天前通过递归编写了这段代码。

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

使用 Jackson 库:

import com.fasterxml.jackson.databind.ObjectMapper;

TypeReference<HashMap<String, Object>> typeRef = new TypeReference<>() {};
Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, typeRef);

【讨论】:

  • 您可以安全地捕获这些异常并抛出运行时异常或断言。您已经检查了该键是否存在,并且该数组在您检查的索引处有一个值。此外,在检查 null 之前创建 retMap 没有任何意义,因为它在 json != null 时创建了两次。不过看起来不错。
  • 这使用什么导入/外部库? Eclipse 无法解散 JSONArray 和 JSONObject
  • @Gewure ,使用 org.json。
  • 在代码中使用 Jackson 库时出现编译时错误。它可以固定如下: TypeReference> typeRef = new TypeReference>() { }; Map 映射 = new ObjectMapper().readValue("", typeRef);
【解决方案2】:

使用Gson,您可以执行以下操作:

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

【讨论】:

  • 但我不想使用 GSon 库。我只能使用“org.json”lirary'。
  • 如何将其读入jsonStringjsonString 和 json 对象有什么区别?
  • @Toon 你可以换个方式吗?
  • @SharpEdge。你的意思是这样的:new Gson().toJson(map);
  • 当使用 Gson 将字符串转换为 hashmap 时,整数被转换为浮点数,这在使用转换后的 Hashmap 时产生了巨大的问题。如果我使用 hashmap,它可以完美运行。但这不是我的情况。我必须使用 hashmap.
【解决方案3】:

希望这会奏效,试试这个:

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

str,你的 JSON 字符串

就这么简单,如果你想要emailid,

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

【讨论】:

  • 选择此解决方案。也很方便,当您的 JSON 字符串意味着具有复杂的数据类型(如列表)时,如 here 所述
  • 因为我事先在我的应用程序中使用了杰克逊库,所以这是我问题的最佳答案。谢谢:)
  • 使用这个解决方案我收到错误 - com.fasterxml.jackson.databind.exc.MismatchedInputException: 无法构造java.util.LinkedHashMap 的实例(尽管至少存在一个创建者):没有字符串参数构造函数/从字符串值反序列化的工厂方法('{
【解决方案4】:

我刚用过Gson

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

【讨论】:

  • 这就是我想要的。
【解决方案5】:

这是 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;
    }
}

【讨论】:

  • 这让我在区分 JsonObject 和 JSONObject 时出错。
  • @sirvon 你能澄清一下吗? JSR 353 代码没有“JSONObject”。我不建议您混合使用 JSON 技术。任选其一。
  • 请注意,生成的 Map 仍然包含包装器(例如 JsonString 而不是纯字符串)。我在这里发布了一个替代解决方案:stackoverflow.com/a/65634179/388827
【解决方案6】:
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;
    }
}

【讨论】:

  • 如果您添加一些解释会很有帮助:您的答案如何改进此问题的其他现有答案
【解决方案7】:

试试这个代码:

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

【讨论】:

    【解决方案8】:

    使用 Jackson 转换:

    JSONObject obj = new JSONObject().put("abc", "pqr").put("xyz", 5);
    
    Map<String, Object> map = new ObjectMapper().readValue(obj.toString(), new TypeReference<Map<String, Object>>() {});
    

    【讨论】:

      【解决方案9】:

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

      【讨论】:

        【解决方案10】:

        您可以使用 Jackson 库将任何 JSON 转换为 map,如下所示:

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

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

        希望这会有所帮助。快乐编码:)

        【讨论】:

          【解决方案11】:

          您也可以为此使用 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);
          

          【讨论】:

            【解决方案12】:

            如果你讨厌递归 - 使用 Stack 和 javax.json 将 Json 字符串转换为 Map 列表:

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

            【讨论】:

              【解决方案13】:

              使用javax.json 发布的here 有一个较旧的答案,但它只转换JsonArrayJsonObject,但输出中仍然有JsonStringJsonNumberJsonValue 包装类。如果你想摆脱这些,这是我的解决方案,它将解开所有内容。

              除此之外,它利用 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());
                  }
              }
              

              【讨论】:

                【解决方案14】:

                您可以使用google gson库来转换json对象。

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

                Jackson 等其他库也可用。

                这不会将其转换为地图。但是你可以做任何你想做的事情。

                【讨论】:

                • 不使用任何封装库也很容易转换。
                【解决方案15】:

                简洁实用:

                /**
                 * @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

                【讨论】:

                  【解决方案16】:

                  以下解析器读取一个文件,使用 Google 的 JsonParser.parse 方法将其解析为通用 JsonElement,然后将生成的 JSON 中的所有项目转换为原生 Java List&lt;object&gt;Map&lt;String, Object&gt;

                  注意:以下代码基于Vikas Guptaanswer

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

                  【讨论】:

                    【解决方案17】:

                    这是一个老问题,可能仍然与某人有关。
                    假设您有字符串 HashMap hash 和 JsonObject jsonObject

                    1) 定义键列表。
                    示例:

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

                    2) 创建foreach循环,从jsonObject添加hash

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

                    这是我的方法,希望它能回答问题。

                    【讨论】:

                      【解决方案18】:

                      想象一下,您有一个如下所示的电子邮件列表。不受任何编程语言的限制,

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

                      【讨论】:

                      • 哪个版本的 Java (6/7/8/9)?哪个版本(SE/EE/Other)?你的代码JSONObject属于哪个包?
                      【解决方案19】:

                      使用json-simple,您可以将数据 JSON 转换为 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);
                      }
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 2021-01-13
                        • 1970-01-01
                        • 2020-07-26
                        • 1970-01-01
                        • 2011-02-02
                        • 2016-06-28
                        • 2014-09-04
                        相关资源
                        最近更新 更多