Convert a JSON String to a HashMap
In recursive way:
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;
}
Using Jackson library:
import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, HashMap.class);
Convert JSON to Map
I hope you were joking about writing your own parser. :-)
For such a simple mapping, most tools from http://json.org (section java) would work.
For one of them (Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:
Map<String,Object> result =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
(where JSON_SOURCE is a File, input stream, reader, or json content String)
creating Hashmap from a JSON String
Parse the JSONObject and create HashMap
public static void jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
System.out.println("json : "+jObject);
System.out.println("map : "+map);
}
Tested output:
json : {"phonetype":"N95","cat":"WP"}
map : {cat=WP, phonetype=N95}
How to convert hashmap to JSON object in Java
You can use:
new JSONObject(map);
Other functions you can get from its documentation
http://stleary.github.io/JSON-java/index.html
How to convert JSON String to HashMap in Rust?
The string is JSON, so you should just parse it. By default serde_json
ignores all unknown fields, so declaring a struct with only the needed fields is enough:
#[derive(serde::Deserialize)]
struct Values {
n: String,
e: String,
}
fn main() -> Result<()> {
let s = r#"{ "kid":"kid-value",
"kty":"RSA",
"use":"sig",
"n":"n-value",
"e":"e-value" }"#;
let value = serde_json::from_str::<Values>(s)?;
println!("{}", value.e);
println!("{}", value.n);
Ok(())
}
How to convert a JSON string to a Map String, String with Jackson JSON
[Update Sept 2020] Although my original answer here, from many years ago, seems to be helpful and is still getting upvotes, I now use the GSON library from Google, which I find to be more intuitive.
I've got the following code:
public void testJackson() throws IOException {
ObjectMapper mapper = new ObjectMapper();
File from = new File("albumnList.txt");
TypeReference<HashMap<String,Object>> typeRef
= new TypeReference<HashMap<String,Object>>() {};
HashMap<String,Object> o = mapper.readValue(from, typeRef);
System.out.println("Got " + o);
}
It's reading from a file, but mapper.readValue()
will also accept an InputStream
and you can obtain an InputStream
from a string by using the following:
new ByteArrayInputStream(astring.getBytes("UTF-8"));
There's a bit more explanation about the mapper on my blog.
Json string to Hashmap Java
JSON string is not valid. If the value of key
is a string, then you need to escape \"
. This means you need to tell to 'Java' to escape also the \
character.
Change the string to String str = "{\"key\":\"[{\\\"one\\\":\\\"value\\\"}]\"}";
This means:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
class Scratch {
public static void main(String[] args) {
String str = "{\"key\":\"[{\\\"one\\\":\\\"value\\\"}]\"}";
ObjectMapper mapper = new ObjectMapper();
try {
HashMap<String, String> map = mapper.readValue(str, HashMap.class);
System.out.println(map);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Map a JSON string into HashMap
You can deserialise it to List<Map<String, Object>>
and later transform to Map
:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./src/main/resources/test.json");
ObjectMapper mapper = new ObjectMapper();
TypeReference rootType = new TypeReference<List<Map<String, Object>>>() { };
List<Map<String, Object>> root = mapper.readValue(jsonFile, rootType);
Map<String, Object> result = root.stream()
.collect(Collectors.toMap(
m -> m.get("map").toString(),
m -> m.get("values")));
System.out.println(result);
}
}
Above code prints:
{TEST2=[test4, test2, test5, test2], TEST=[test, test2], TEST1=[test, test3, test4]}
Related Topics
Add Jar Files to a Spark Job - Spark-Submit
Using "Like" Wildcard in Prepared Statement
When Is the @JSONproperty Property Used and What Is It Used For
How to Use an Internet Time Server to Get the Time
Java.Lang.Unsatisfiedlinkerror No *****.Dll in Java.Library.Path
Get Source Jars from Maven Repository
How to Get a Unique Computer Identifier in Java (Like Disk Id or Motherboard Id)
Spring MVC: How to Perform Validation
Does the Jvm Prevent Tail Call Optimizations
How to Make an Http Request Using Cookies on Android
Java Nio Filechannel Versus Fileoutputstream Performance/Usefulness
How to Get the SQL of a Preparedstatement
Effective Gif/Image Color Quantization