Convert JSON to Map

后端 未结 17 2861
天涯浪人
天涯浪人 2020-11-22 10:20

What is the best way to convert a JSON code as this:

{ 
    \"data\" : 
    { 
        \"field1\" : \"value1\", 
        \"field2\" : \"value2\"
    }
}


        
相关标签:
17条回答
  • 2020-11-22 10:53

    I do it this way. It's Simple.

    import java.util.Map;
    import org.json.JSONObject;
    import com.google.gson.Gson;
    
    public class Main {
        public static void main(String[] args) {
            JSONObject jsonObj = new JSONObject("{ \"f1\":\"v1\"}");
            @SuppressWarnings("unchecked")
            Map<String, String> map = new Gson().fromJson(jsonObj.toString(),Map.class);
            System.out.println(map);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 10:55

    Try this code:

      public static Map<String, Object> convertJsonIntoMap(String jsonFile) {
            Map<String, Object> map = new HashMap<>();
            try {
                ObjectMapper mapper = new ObjectMapper();
                mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
                mapper.readValue(jsonFile, new TypeReference<Map<String, Object>>() {
                });
                map = mapper.readValue(jsonFile, new TypeReference<Map<String, String>>() {
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
            return map;
        }
    
    0 讨论(0)
  • 2020-11-22 10:56

    One more alternative is json-simple which can be found in Maven Central:

    (JSONObject)JSONValue.parse(someString); //JSONObject is actually a Map.
    

    The artifact is 24kbytes, doesn't have other runtime dependencies.

    0 讨论(0)
  • 2020-11-22 10:58

    Using the GSON library:

    import com.google.gson.Gson;
    import com.google.common.reflect.TypeToken;
    import java.lang.reclect.Type;
    

    Use the following code:

    Type mapType = new TypeToken<Map<String, Map>>(){}.getType();  
    Map<String, String[]> son = new Gson().fromJson(easyString, mapType);
    
    0 讨论(0)
  • 2020-11-22 10:59

    This way its works like a Map...

    JSONObject fieldsJson = new JSONObject(json);
    String value = fieldsJson.getString(key);
    
    <dependency>
        <groupId>org.codehaus.jettison</groupId>
        <artifactId>jettison</artifactId>
        <version>1.1</version>
    </dependency>
    
    0 讨论(0)
  • 2020-11-22 10:59

    The JsonTools library is very complete. It can be found at Github.

    0 讨论(0)
提交回复
热议问题