Gson java map to json

How to serialize a Map of a Map with GSON?

It seems that GSON cannot serialize the Map Range inside the Map General . Is this a limitation of GSON or am I doing something wrong here?

If other answers are correct and default Map serializer won’t handle nested maps, I would file a bug report for GSON team. It seems like really bad defaults to me; at least it ought to throw an exception instead of quietly swallowing contents.

+1 @StaxMan it seems like that. I have seen this earlier, came up with some work-around. If there is some way to do this, it’s worth documentation.

3 Answers 3

The reason why Nishant’s answer works is because Gson’s default constructor enables all kind of stuff per default that you would otherwise have to manually enably using the GsonBuilder.

  • The JSON generated by toJson methods is in compact representation. This means that all the unneeded white-space is removed. You can change this behavior with GsonBuilder.setPrettyPrinting().
  • The generated JSON omits all the fields that are null. Note that nulls in arrays are kept as is since an array is an ordered list. Moreover, if a field is not null, but its generated JSON is empty, the field is kept. You can configure Gson to serialize null values by setting GsonBuilder.serializeNulls().
  • Gson provides default serialization and deserialization for Enums, Map, java.net.URL, java.net.URI, java.util.Locale, java.util.Date, java.math.BigDecimal, and java.math.BigInteger classes. If you would prefer to change the default representation, you can do so by registering a type adapter through GsonBuilder.registerTypeAdapter(Type, Object).
  • The default Date format is same as java.text.DateFormat.DEFAULT. This format ignores the millisecond portion of the date during serialization. You can change this by invoking GsonBuilder.setDateFormat(int) or GsonBuilder.setDateFormat(String).
  • By default, Gson ignores the com.google.gson.annotations.Expose annotation. You can enable Gson to serialize/deserialize only those fields marked with this annotation through GsonBuilder.excludeFieldsWithoutExposeAnnotation().
  • By default, Gson ignores the com.google.gson.annotations.Since annotation. You can enable Gson to use this annotation through GsonBuilder.setVersion(double).
  • The default field naming policy for the output Json is same as in Java. So, a Java class field versionNumber will be output as «versionNumber@quot; in Json. The same rules are applied for mapping incoming Json to the Java classes. You can change this policy through GsonBuilder.setFieldNamingPolicy(FieldNamingPolicy).
  • By default, Gson excludes transient or static fields from consideration for serialization and deserialization. You can change this behavior through GsonBuilder.excludeFieldsWithModifiers(int).
Читайте также:  Php simplexml load string as xml

OK, now I see what the problem is. The default Map serializer, as you expected, does not support nested maps. As you can see in this source snippet from DefaultTypeAdapters (especially if you step through with a debugger) the variable childGenericType is set to the type java.lang.Object for some mysterious reason, so the runtime type of the value is never analysed.

  1. Implement your own Map serializer / deserializer
  2. Use a more complicated version of your method, something like this:

Источник

Gson – Serialize and Deserialize a Map

Learn to serialize HashMap using Google Gson library. Also, learn to deserialize JSON string to HashMap containing custom Objects using Gson such that field values are copied into appropriate generic types.

These conversions can be used to create deep cloning of the HashMap.

Include the latest version of Gson into the project runtime.

 com.google.code.gson gson 2.10.1 

Serializing a hashmap to JSON using Gson is an easy process. Just use gson.toJson() method to get the JSON string obtained after converting HashMap.

Java program to convert HashMap to JSON string using Gson.

Map map = Map.of( 1, new User(1L, "lokesh", "gupta", LocalDate.of(1999, Month.JANUARY, 1), new Department(1, "IT", true)), 2, new User(2L, "alex", "gussin", LocalDate.of(1988, Month.MARCH, 31), new Department(2, "FINANCE", true))); Gson gson = new GsonBuilder() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) .create(); String jsonString = gson.toJson(map); System.out.println(jsonString);

Here the User and Department classes are given as:

@Data @NoArgsConstructor @AllArgsConstructor @ToString public class User < private Long id; private String firstName; private String lastName; private LocalDate dateOfbirth; private Department department; >@Data @NoArgsConstructor @AllArgsConstructor @ToString public class Department

To deserialize JSON string back to HashMap involves two steps:

  • Create com.google.gson.reflect.TypeToken which represents a generic type. It forces clients to create a subclass of this class which enables retrieval of the type information even at runtime.
  • Use gson.fromJson() method to get HashMap from JSON string.

Java program to parse JSON to HashMap object containing generic types.

Gson gson = new GsonBuilder() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) .create(); Type mapType = new TypeToken>()<>.getType(); HashMap usersMap = gson.fromJson(jsonString, mapType); System.out.println(usersMap);

Источник

How to Convert Java Map to JSON

Last updated: 12 November 2019 There are a number of ways to convert a Java Map into JSON. It is quite common to convert Java Arrays and Maps into JSON and vice versa. In this post, we look at 3 different examples to convert Java Map to JSON. We will be using Jackson, Gson and org.json libraries.

Java Map to JSON using Jackson

The following example uses Jackson Core and Jackson Binding to convert Java Map to JSON. In order to use the Jackson libraries, we first need to add them to our pom.xml file:

  com.fasterxml.jackson.core jackson-core 2.9.8  com.fasterxml.jackson.core jackson-databind 2.9.8   
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; public class ConvertJavaMapToJson < @Test public void convertMapToJson() < Mapelements = new HashMap(); elements.put("Key1", "Value1"); elements.put("Key2", "Value2"); elements.put("Key3", "Value3"); ObjectMapper objectMapper = new ObjectMapper(); try < String json = objectMapper.writeValueAsString(elements); System.out.println(json); >catch (JsonProcessingException e) < e.printStackTrace(); >> > 

As can be seen from the output, the order of the elements in the JSON are not the same as the order we added them to the map. To retain the order, we need to use SortedMap instead. e.g.

SortedMap elements = new TreeMap(); 

Java Map to JSON using Gson

The following example uses Gson library to convert Java Map to JSON, but first, we need to add Gson as a dependency to pom.xml file.

  com.google.code.gson gson 2.8.5   
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.junit.jupiter.api.Test; import java.lang.reflect.Type; import java.util.HashMap; import java.util.SortedMap; import java.util.TreeMap; public class ConvertJavaMapToJson < @Test public void convertMapToJson() < SortedMapelements = new TreeMap(); elements.put("Key1", "Value1"); elements.put("Key2", "Value2"); elements.put("Key3", "Value3"); Gson gson = new Gson(); Type gsonType = new TypeToken()<>.getType(); String gsonString = gson.toJson(elements,gsonType); System.out.println(gsonString); > > 

Java Map to JSON using org.json

The following example uses org.json library to convert Java Map to JSON, but first, we need to add org.json as a dependency to pom.xml file.

import org.json.JSONObject; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; public class ConvertJavaMapToJson < @Test public void convertMapToJson() < Mapelements = new HashMap<>(); elements.put("Key1", "Value1"); elements.put("Key2", "Value2"); elements.put("Key3", "Value3"); JSONObject json = new JSONObject(elements); System.out.println(json); > > 

Источник

Gson шпаргалка для Map, List и Array

Постоянно сталкиваясь с парсингом Json всегда подглядываю в старых проектах или на встретившуюся реализацию объекта на stackoverflow.com.

Решил собрать три основных типа в шпаргалку Map, List, Array.

Type itemsMapType = new TypeToken>() <>.getType(); Type itemsListType = new TypeToken>() <>.getType(); Type itemsArrType = new TypeToken() <>.getType(); 

Рассматривается Serialization/Deserialization операции класса:

Serialization/Deserialization выполнен с использованием библиотеки Gson. В качестве «испытуемого» рассматривается класс GoodsItem.

Map mapItems = new HashMap(); mapItems.put(1, new GoodsItem("Samsung", 51200.6f)); mapItems.put(2, new GoodsItem("Lg", 5400.6f)); mapItems.put(3, new GoodsItem("Alcatel", 4500.6f)); String jsonStr = new Gson().toJson(mapItems); System.out.println(jsonStr); 
Map mapItemsDes = new Gson().fromJson(jsonStr, itemsMapType); System.out.println(mapItemsDes.toString()); 
List listItems = new ArrayList(); listItems.add( new GoodsItem("Samsung" , 51200.6f)); listItems.add( new GoodsItem("Lg" , 5400.6f)); listItems.add( new GoodsItem("Alcatel" , 4500.6f)); String jsonStr = new Gson().toJson(listItems); System.out.println(jsonStr); 
List listItemsDes = new Gson().fromJson(jsonStr,itemsListType); System.out.println(listItemsDes.toString()); 
[Samsung : 51200.6, Lg : 5400.6, Alcatel : 4500.6] 
GoodsItem[] arrItems = new GoodsItem[3]; arrItems[0] = new GoodsItem("Samsung", 51200.6f); arrItems[1] = new GoodsItem("Lg", 5400.6f); arrItems[2] = new GoodsItem("Alcatel", 4500.6f); String jsonStr = new Gson().toJson(arrItems); System.out.println(jsonStr); 
GoodsItem[] arrItemsDes = new Gson().fromJson(jsonStr, itemsArrType); System.out.println(Arrays.toString(arrItemsDes)); 
[Samsung : 51200.6, Lg : 5400.6, Alcatel : 4500.6] 

Как видно ArrayList и простой массив объектов преобразуются в одинаковую строку Json.

Полезные инструменты:
parcelabler.com дает возможность по типу класса сгенерировать parcelable методы для Android. Например для класса GoodsItem:

public class GoodsItem implements Parcelable < String name; float price; public GoodsItem(String name, float price) < this.name = name; this.price = price; public String toString()< return name + " : " + price; >protected GoodsItem(Parcel in) < name = in.readString(); price = in.readFloat(); >@Override public int describeContents() < return 0; >@Override public void writeToParcel(Parcel dest, int flags) < dest.writeString(name); dest.writeFloat(price); >@SuppressWarnings("unused") public static final Parcelable.Creator CREATOR = new Parcelable.Creator() < @Override public GoodsItem createFromParcel(Parcel in) < return new GoodsItem(in); >@Override public GoodsItem[] newArray(int size) < return new GoodsItem[size]; >>; > 

jsonschema2pojo.org — Generate Plain Old Java Objects from JSON or JSON-Schema.

Было бы интересно узнать, чем пользуетесь вы в своих проектах.

Источник

Оцените статью