How to Convert Json to a Hashmap Using Gson

How can I convert JSON to a HashMap using Gson?

Here you go:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson("{'k1':'apple','k2':'orange'}", type);

json array in hashmap using google gson

Your JSON is an array of objects, not anything resembling a HashMap.

If you mean you're trying to convert that to a List of HashMaps ... then that's what you need to do:

Gson gson = new Gson();
Type listType = new TypeToken<List<HashMap<String, String>>>(){}.getType();
List<HashMap<String, String>> listOfCountry =
gson.fromJson(sb.toString(), listType);

Edit to add from comments below:

If you would like to deserialize to an array of Country POJOs (which is really the better approach), it's as simple as:

class Country {
public String countryId;
public String countryName;
}
...
Country[] countryArray = gson.fromJson(myJsonString, Country[].class);

That said, it's really better to use a Collection:

Type listType = new TypeToken<List<Country>>(){}.getType();
List<Country> countryList = gson.fromJson(myJsonString, listType);

How to convert JSON fields into a JAVA map using GSON

Declaring Alert object like this:

public class Alert {
private String description;
private String status;
private Map<String, String> labels;
...
}

works for me and this code

Alert myAlert = gson.fromJson(alertJSON, Alert.class);
System.out.println(myAlert.getLabels());

prints the map as {field1=value1, field2=value2, field100=value100}

So that no intermediate object is required

JSON to hashmap with GSON

If you add a closing } to

{
"someText": {
"text1": "lorem ipsum",
"text2": "ipsum lorem"
}}
^

thus making your JSON well formed, the following

myTexts t = new Gson().fromJson(myJsonFile, myTexts.class);
System.out.println(t.someText);

prints

{text1=lorem ipsum, text2=ipsum lorem}

which seems to be what you are expecting.

Gson to HashMap

Use TypeToken, as per the GSON FAQ:

Gson gson = new Gson();
Type stringStringMap = new TypeToken<Map<String, String>>(){}.getType();
Map<String,String> map = gson.fromJson(json, stringStringMap);

No casting. No unnecessary object creation.

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

Parsing JSON object into a Map using Gson - JsonSyntaxException

it is easy to check:

    Map<String,Attribute> attributes = new HashMap<>();
attributes.put("key_0", new Attribute("value_0", "name_0"));// I added constructor and getter/setter methods to class Attribute
attributes.put("key_1", new Attribute("value_1", "name_1"));
attributes.put("key_2", new Attribute("value_2", "name_2"));
//serialize using ObjectMapper
ObjectMapper mapper = new ObjectMapper();
var s = mapper.writeValueAsString(attributes);
System.out.println(s);

output:

{
"key_2":{
"value":"value_2",
"name":"name_2"
},
"key_1":{
"value":"value_1",
"name":"name_1"
},
"key_0":{
"value":"value_0",
"name":"name_0"
}
}

How to convert nested json into Map without typecasting using Gson

I would say you can convert the json string into Map<String, JsonElement> so that you have so methods to find nested object is JsonObject or JsonArray. So in the blow example main is key with JsonObject as value

main: {
temp:8.1,
pressure:1007.0,
humidity=93.0,
temp_min=7.0,
temp_max=10.0
}

You can parse the value into Map by using fromJson

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

for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
System.out.println(entry);
}

System.out.println(resultMap.get("temp"));
Map<String, Object> mainMap = new Gson().fromJson(resultMap.get("main").toString(), new TypeToken<Map<String, Object>>() {
}.getType());
System.out.println("Temp: " + mainMap.get("temp"));


Related Topics



Leave a reply



Submit