Creating Hashmap from a JSON 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}

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

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

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

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)

How to convert a JSON string to a MapString, 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.

How to properly convert HashMapString,ListObject to Json with array of json object

It is now working using these changes:

HashMap<String,List<Object>> responses = new HashMap<String,List<Object>>();

for (ConsumerRecord<String,String> consumerRecord : records) {
if(!responses.containsKey(consumerRecord.topic())){
responses.put(consumerRecord.topic(), new ArrayList<Object>());
}
responses.get(consumerRecord.topic()).add(new JSONObject(consumerRecord.value()));
}

jsonObject = new JSONObject(responses);
return jsonObject.toMap();

  1. Convert Kafka message string to JSONObject new JSONObject(consumerRecord.value())
  2. Construct a JSONObject from a Map using
    jsonObject = new JSONObject(responses);
  3. Return Map<String, Object> using jsonObject.toMap();

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


Related Topics



Leave a reply



Submit